Loading lessons...
The self Parameter
The self Parameter
self is the first parameter of every method, and it always refers to the object that called the method.
self carries the object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc() # Hello my name is John
You don't pass self
When you call p1.myfunc(), Python passes p1 as self automatically. You only write the other arguments.
You can name it anything
self is a convention, not a keyword. This also works:
class Person:
def __init__(anything, name):
anything.name = name
But always use self so others can read your code.
Modify object properties
self lets methods change the object:
p1.age = 40 # outside the class
or
def set_age(self, age):
self.age = age
Delete object properties
del removes an attribute or the whole object:
del p1.age
del p1
TL;DR
selfis the first parameter of every method.- It refers to the object that called the method.
- Python passes it automatically; you never write it at the call.
- Use it to read and change the object's attributes.