self代表的是类的实例。
>>> class Test:
... def prt(self):
... print(self)
... print(self.__class__)
...
>>> t = Test()
>>> t.prt()
<__main__.Test object at 0x000001ADE41B1710>
<class '__main__.Test'>
# self代表的是类的实例。而self.__class__则指向类。
>>> t
<__main__.Test object at 0x000001ADE41B1710>
# 在Python的解释器内部,当我们调用t.prt()时,实际上Python解释成Test.prt(t),也就是说把self替换成类的实例。
>>> Test.prt(t)
<__main__.Test object at 0x000001ADE41B1710>
<class '__main__.Test'>
>>>
使用类方法中的变量,需要实例化方法
>>> class A(object):
... def go(self):
... self.one = "hello"
...
>>> a1 = A()
>>> a1.go()
>>> a1.one
'hello'
# 使用类方法中的变量,需要实例化方法
>>> a2 = A()
>>> a2.one
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'one'
类方法中变量用self修饰,等价于是全局变量;不用self修饰,相当于是局部变量。
# 用self修饰类方法中的变量,相当于是全局变量
>>> class A:
... def prt(self):
... self.temp = "global_val"
...
>>> a = A()
>>> a.prt()
>>> a.temp
'global_val'
# 不用self修饰类方法中的变量,相当于是局部变量
>>> class B:
... def prt(self):
... temp = "local_val"
...
>>> b = B()
>>> b.prt()
>>> b.temp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'B' object has no attribute 'temp'
>>>
- 类方法中需要用self修饰,非类方法不需要用self
- self是可以替换成别的单词的,它不是关键字。但是为了约定俗成,我们还是一致使用self。