全面理解python中self的用法 |
您所在的位置:网站首页 › python的self的用法 › 全面理解python中self的用法 |
全⾯理解 python 中 self 的⽤法 self 代表类的实例,⽽⾮类。 class Test:
def prt(self):
(self)
(self. __class__ )
t = Test() t.prt() 执⾏结果如下
从上⾯的例⼦中可以很明显的看出, self 代表的是类的实例。⽽ self.class 则指向类。 self 不必⾮写成 self 把上⾯的代码改写⼀下。 class Test:
def prt(this):
(this)
(this. __class__ )
t = Test() t.prt() 改成 this 后,运⾏结果完全⼀样。 当然,最好还是尊重约定俗成的习惯,使⽤ self 。 self 可以不写吗 在 Python 的解释器内部,当我们调⽤ t.prt() 时,实际上 Python 解释成 Test.prt(t) ,也就是说把 self 替换成类的实例。 把上⾯的 t.prt() ⼀⾏改写⼀下,运⾏后的实际结果完全相同。 实际上已经部分说明了 self 在定义时不可以省略 class Test:
def prt():
(self)
t = Test() t.prt() 运⾏时提醒错误如下: prt 在定义时没有参数,但是运⾏时强⾏传了⼀个参数。 由于上⾯解释过了 t.prt() 等同于 Test.prt(t) ,所以程序提醒多传了⼀个参数 t 。 Traceback (most recent call last): File "h.py" , line 6, in
t.prt() TypeError: prt() takes 0 positional arguments but 1 was given 如果 定义和调⽤时均不传类实例是可以的,就是类⽅法 。 class Test:
def prt():
( __class__ ) Test.prt() 运⾏结果如下
在继承时,传⼊的是哪个实例,就是那个传⼊的实例,⽽不是指定义了 self 的类的实例。 先看代码 class Parent:
def pprt(self):
(self)
class Child(Parent): |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |