Home > Article > Backend Development > Is self redundant in python?
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()The execution results are as follows
<__main__.Test object at 0x000000000284E080> <class '__main__.Test'>From It is obvious from the above example that self represents an instance of a class. And self.class points to the class.
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()The runtime reminder error is as follows: prt has no parameters when defining, but a parameter is forcibly passed during runtime. As explained above, t.prt() is equivalent to Test.prt(t), so the program reminds that one more parameter t is passed.
Traceback (most recent call last): File "h.py", line 6, in <module> t.prt() TypeError: prt() takes 0 positional arguments but 1 was givenIt is okay if you do not pass a class instance when defining and calling, it is a class method.
class Test: def prt(): print(__class__) Test.prt()The running results are as follows
<class '__main__.Test'>When inheriting, which instance is passed in is the instance passed in, not the instance of the class in which self is defined. Look at the code first
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()The running results are as follows
<__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!