python类中的self是什么?
同一个类可以产生多个对象,当某个对象调用类方法时,该对象会把自身的引用作为第一个参数自动传给该方法,换句话说,Python 会自动绑定类方法的第一个参数指向调用该方法的对象,不需要手动为第一个参数传值。这样Python解释器就能知道到底要操作哪个对象的方法了。类似于Java中的this。
比如:
class Song(object):
def __init__(self,lyrics): #初始化
self.lyrics = lyrics
def sing_me_a_song(self): #创建一个实例方法
for line in self.lyrics:
print(line)
#创建两个类对象
happy_bday = Song(["happy birthday to you"])
bulls_on_parade = Song(["they rally around tha family",
"with pockets full of shells"])
#分别调用类的同一方法
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
其中,*happy_bday.sing_me_a_song()*的执行结果为:
happy birthday to you
而bulls_on_parade.sing_me_a_song()执行结果为:
they rally around tha family
with pockets full of shells
上面代码中,sing_me_a_song(self)中的 self 代表该方法的调用者。即谁调用该方法,那么 self 就代表谁。Python 规定,无论是构造方法还是实例方法,最少要包含一个参数,而参数名程序员间约定俗成为“self”。
参考:http://c.biancheng.net/view/2266.html