Object Initialization and the self Argument
It's often not understood immediately, so just start using it and understanding will come sooner or later on its own.
class Person:
def __init__(self, name, age):
self.name = name # We store these variables inside the instance
self.age = age
# You can think of these as global variables of the instance that you create from the class
def get_data(self): # In each method, the 1st argument is self
# We can access these variables from anywhere
print(f"name: {self.name}\nage: {self.age}")
a = Person("Alex", 10) # These arguments go to __init__
b = Person("John", 19) # And then are stored in the global scope of the instance
What is self?
self is used as the first argument in class methods. It is used to refer to the class instance for which the method is called. When you call a method, Python automatically passes the object as the first argument of the method (self). By convention, this argument is called self. This allows the method to access and manipulate the attributes of the object for which it was called. Also, inside methods, you can access all values that are bound to the instance through self.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_data(self):
print(f"{self.name}:{self.age}")
person = Person("John", 30)
person.get_data()
When we create an instance of the Person class and call get_data, we don't need to explicitly pass the instance as an argument. Python automatically passes the object as the first argument of the method. This allows us to write methods that manipulate the attributes of the object for which they are called. This approach simplifies the creation of reusable code that works with different instances of the same class.
Comments (0)