self 的意思是“自己”,表示的是对象自身,当某个对象调用成员方法的时候,Python 解释器会自动把当前对象作为第1个参数传给 self ,用户只需要传递后面的参数就可以了。
self 参数的应用:
#program0706.py self 参数的应用
class Animal:'''类中未定义构造方法,使用默认的构造方法def __init__(self):self.color = color'''num = 0 #类的属性#enjoy()方法没有self参数,普通的方法,由类名调用def enjoy(): #这里是一个普通函数,由类名调用print("汪汪汪")#show()方法使用self参数,成员方法def show(self):print("重量{}千克".format(self.weight))
ani = Animal()
ani.weight = 52
Animal.enjoy() #ani.enjoy()错误
ani.show()
运行结果: