Lesson 75 +10 XP

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


python
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:


python
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:


python
p1.age = 40

### outside the class

or


python
def set_age(self, age):
    self.age = age

Delete object properties

del removes an attribute or the whole object:


python
del p1.age
del p1

TL;DR

  • self is 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.