self represents an instance of a class, not a class.
## Let’s look at an example first:
class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt()
<__main__.Test object at 0x000000000284E080> <class '__main__.Test'>
Can I not write self?
Inside the Python interpreter, when we call t.prt(), Python is actually interpreted as Test.prt(t ), that is to say, replace self with an instance of the class. Rewrite the t.prt() line above, and the actual results after running will be exactly the same. In fact, it has been partially explained that self cannot be omitted when definingclass Test: def prt(): print(self) t = Test() t.prt()
Traceback (most recent call last): File "h.py", line 6, in <module> t.prt() TypeError: prt() takes 0 positional arguments but 1 was given
class Test: def prt(): print(__class__) Test.prt()
<class '__main__.Test'>
class Parent: def pprt(self): print(self) class Child(Parent): def cprt(self): print(self) c = Child() c.cprt() c.pprt() p = Parent() p.pprt()
<__main__.Child object at 0x0000000002A47080> <__main__.Child object at 0x0000000002A47080> <__main__.Parent object at 0x0000000002A47240>
Explanation:
You should not understand when running c.cprt() Question, refers to an instance of Child class. But when running c.pprt(), it is equivalent to Child.pprt(c), so self still refers to an instance of the Child class. Since the pprt() method is not defined in self, So I looked up the inheritance tree and found that the pprt() method was defined in the parent class Parent, so it will be called successfully.Summary
self needs to be defined when defining, but it will be automatically passed in when called. The name of self is not stipulated, but it is best to use self according to the conventionself always refers to the instance of the class when calling.The above is the detailed content of Is self redundant in python?. For more information, please follow other related articles on the PHP Chinese website!