#Python self Parameter
The self parameter is a reference to the current instance of the class. It is used to access variables and methods that belong to that specific object.
#Why Use self?
Without self, Python would not know which object's properties you are trying to access. It acts as the link between the method and the specific instance of the class.
Example: Linking methods to specific objects
pythonclass Person:
def __init__(self, name):
self.name = name
def printname(self):
print(self.name)
p1 = Person("Tobias")
p2 = Person("Linus")
p1.printname()
p2.printname()
#Key Rules for self
- Position: It must be the first parameter of any method in the class.
- Naming: It does not strictly have to be named
self. You can call it whatever you like (e.g.,myobjectorabc), but it must remain the first parameter. - Convention: While other names work, it is strongly recommended to use
selfto follow Python’s standard naming conventions and ensure code readability.
Example: Using custom names instead of self
pythonclass 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
You can access any property of the class by prefixing the variable name with self.
Example: Accessing multiple properties
pythonclass 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 is also used to call other methods within the same class.
Example: Calling one method from another
pythonclass 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()