Python Classes
Python self Parameter
Understanding self
Python self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
What is self?
self is not a keyword in Python, but it's a convention. It refers to the instance of the class:
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
return f"My name is {self.name}"
person = Person("John")
print(person.introduce())
Why self is Important
Without self, you cannot access instance variables or methods:
class Person:
def __init__(self, name):
self.name = name # Instance variable
def get_name(self):
return self.name # Accessing instance variable