Week 12: Introduction to Object-Oriented Programming
Get a taste of object-oriented programming in Python.
Explore Chapter 12The `self` Parameter.
The `self` parameter is the first parameter in every instance method definition. It's a reference to the instance of the class (the object itself). When you call a method on an object, Python automatically passes the object itself as the first argument to the method, and that argument is assigned to the `self` parameter.
You use `self` to access the object's attributes and call other methods on the object from within the method.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person1 = Person("Alice", 28)
person1.greet() # Output: Hello, my name is Alice and I am 28 years old.
Although you can name the first parameter of an instance method something other than `self`, it is a strong convention to always use `self`, and you should stick to it.