The self Parameter
Inside a method, self refers to the particular instance of the class the method is working on.
Through it, you reach the properties and methods that belong to the class.
Note: In every method of the class, self has to come first in the parameter list.
Example
Read a class property through self:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
p1 = Person("Emil", 25)
p1.greet()
Why Use self?
self is how Python knows which object's properties you mean. Without it, there would be no way to tell:
Example
Thanks to self, the method works with the object it was called on:
Output: complete Python program
class Person:
def __init__(self, name):
self.name = name
def printname(self):
print(self.name)
p1 = Person("Tobias")
p2 = Person("Linus")
p1.printname()
p2.printname()
self Does Not Have to Be Named "self"
The name itself is not required. Any name will do, as long as that parameter comes first in each method of the class:
Note: Just because you can pick another name does not mean you should. self is the Python convention, and sticking to it makes your code easier for others to read.
Example
Here myobject and abc take the place of self:
Output: complete Python program
class Person:
def __init__(myobject, name, age):
myobject.name = name
myobject.age = age
def greet(abc):
print("Hello, my name is " + abc.name)
p1 = Person("Emil", 36)
p1.greet()
Accessing Properties with self
Every property of the class is within reach through self:
Example
Read several properties through self:
Output: complete Python program
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.brand} {self.model}")
car1 = Car("Toyota", "Corolla", 2020)
car1.display_info()
Calling Methods with self
self also lets a method call other methods of the same class:
Example
One method calls another through self:
Output: complete Python program
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return "Hello, " + self.name
def welcome(self):
message = self.greet()
print(message + "! Welcome to our website.")
p1 = Person("Tobias")
p1.welcome()