Analysis of Python definition class self usage instance

Time:2020-3-21

This article mainly introduces the example analysis of self usage of Python definition class. The example code is introduced in detail in this article, which has a certain reference value for your study or work. You can refer to the following for friends who need it

In the process of defining a class, whether it is to explicitly create a class construction method or to add an instance method to a class, the self parameter should be taken as the first parameter of the method.

class Person:
def __init__(self):
Print (“executing constructor”)
def study(self, name):
Print (name, “learning Python”)
The self parameter in Python class method is equivalent to this pointer in C + +.
The same class can generate multiple objects. When an object calls a class method, the object will automatically pass its reference to the method as the first parameter. In other words, python will automatically bind the first parameter of the class method to the object calling the method.
In this way, the Python interpreter can know which method to operate on.

When a program calls an instance method and a construction method, it does not need to manually pass values for the first parameter.

class Person:
def __init__(self):
Print (“executing constructor”)
def study(self):
Print (self, “learning Python”)
xiaobai = Person()
xiaobai.study()
mary = Person()
mary.study()
#Execution results
#Self in study () represents the caller of the method, that is, who calls the method, then self represents who.
Executing construction method
< main.person object at 0x0000013b6a24ba58 > learning Python
Executing construction method
< main.person object at 0x0000013b6a24bc88 > learning Python
For the self parameter in the constructor, it represents the class object currently being initialized.

class Person:
  name = "xiaobai"
  def __init__(self, name):
    self.name = name
mary = Person("mary")
print(mary.name)
lisa = Person("lisa")
print(lisa.name)
#Execution results
mary
lisa

In a word, no matter the constructors in a class or ordinary class methods, who actually calls them, then self represents who.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.