What is the purpose of the self parameter in Python?

In Python, self is a special parameter used to access the attributes and methods of an object. It is passed as the first parameter in a class method and refers to the object that is calling the method itself.

In particular, the self parameter is used in a class’s methods to access the instance variables and methods of that class. Through self, you can retrieve and modify an object’s properties, as well as call other instance methods. The self parameter can be understood as a reference to the object itself, allowing you to differentiate between different objects.

Here is an example demonstrating the usage of ‘self’:

class MyClass:
    def __init__(self, name):
        self.name = name  # 使用self访问实例变量

    def say_hello(self):
        print("Hello, " + self.name)  # 使用self访问实例变量

my_obj = MyClass("Alice")
my_obj.say_hello()  # 输出 "Hello, Alice"

In the examples above, the self parameter is utilized in the __init__ and say_hello methods. In the __init__ method, self is used to access and initialize the instance variable name. In the say_hello method, self is used to access the instance variable name and print the output.

It is important to note that the name of the self parameter is not fixed, it can be chosen as a different name, but the common practice is to use self as the parameter name. By using the self parameter, the methods of the class can properly access and operate the object’s attributes and methods.

bannerAds