ID = python_ask_00
Question
How to understand self?
Answer
- To define a method inside class, need to contain self as the first arguments.
- self is instance of the class, which represents address of current object.
- self is not key word of Python, and can be replaced with this or mine, etc. But people use it normally.
Example 1
#!/usr/bin/python3
class Test():
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
<__main__.Test object at 0x7f6dce064640>
从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。
Example 2
Another example [1]:
class Parent:
def pprt(self):
print(self)
class Child(Parent):
def cprt(self):
print(self)
c = Child() # this is instantiation
c.cprt() # this is invoking
c.pprt()
p = Parent()
p.pprt()
The result is:
<__main__.Child object at 0x0000000002A47080>
<__main__.Child object at 0x0000000002A47080>
<__main__.Parent object at 0x0000000002A47240>
解释:
运行c.cprt()时应该没有理解问题,指的是Child类的实例。
但是在运行c.pprt()时,等同于Child.pprt©,所以self指的依然是Child类的实例,由于self中没有定义pprt()方法,所以沿着继承树往上找,发现在父类Parent中定义了pprt()方法,所以就会成功调用。
self在定义时需要定义,但是在调用时会自动传入。
self总是指调用时的类的实例, in other words, self is representing current object.