self in Python
- ‘self’ represents instance, rather than the class.
- When we are running t.prt(), actually we are running Test.prt(t).
-
Class Test: def prt(self): print(self) t = Test() t.prt()
- The Class Method: (Not passing self when we are defining and calling the function.)
-
class Test: def prt(): print(__class__) Test.prt()
- 在继承时,传入的是哪个实例,那么父类中运行的也是这个实例。
- 在描述符类中,self指的是描述符类的实例。
-
class Desc: def __get__(self, ins, cls): print('self in Desc: %s ' % self ) print(self, ins, cls) class Test: x = Desc() def prt(self): print('self in Test: %s' % self) t = Test() t.prt() t.x
运行结果:
-
self in Test: <__main__.Test object at 0x0000000002A570B8> self in Desc: <__main__.Desc object at 0x000000000283E208> <__main__.Desc object at 0x000000000283E208> <__main__.Test object at 0x0000000002A570B8> <class '__main__.Test'>
- Reference: 一篇文章让你彻底搞清楚Python中self的含义