This Python self Parameter lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
self is the object the method was called on. learner.label() passes learner as self.
The name self is a convention, not a keyword. Stick to it so other readers recognise it.
Example 1: Start here
Calling add on c changes c, not some other counter.
class Counter: # a template for objects
def __init__(self): # runs when you create the object
self.value = 0 # store this on the object
def add(self): # define the function; it runs when you call it
self.value += 1 # update the stored value
return self.value # send this value back to the caller
c = Counter() # one object
print(c.add())
print(c.add())
Example 2: self is the object
python.show() passes python into self.
class Course: # a template for objects
def __init__(self, title): # runs when you create the object
self.title = title # store this on the object
def show(self): # define the function; it runs when you call it
return self.title # send this value back to the caller
python = Course("Python") # one object
print(python.show())
Example 3: Two objects, two selves
Each object has its own title. self always means the current one.
class Course: # a template for objects
def __init__(self, title): # runs when you create the object
self.title = title # store this on the object
print(Course("Python").title)
print(Course("SQL").title)
Example 4: Update through self
self.seats changes the object that add was called on.
class Course: # a template for objects
def __init__(self, seats): # runs when you create the object
self.seats = seats # store this on the object
def add(self, more): # define the function; it runs when you call it
self.seats += more # update the stored value
course = Course(20) # one object
course.add(4)
print(course.seats)
