python_ask_00-How to understand *self*?

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.

Reference

[1] 一篇文章让你彻底搞清楚Python中self的含义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值