之前一直自学python时一直对类中的self感到困惑,不明白他到底怎么起效,直到刷B站看到视频给了启发
self其实就是代指你自己后来定义的实例,看代码
class animal():
def eat(self, food):
print(f"在吃{food}")
此时定义一个实例:
dog = animal()
执行eat函数有两种方法:
animal.eat(dog, "狗粮")
dog.eat("狗粮")
此时结果均为
在吃狗粮
但是当同时使用两种方法时:
dog.eat(dog, "狗粮")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [11], in <cell line: 1>()
----> 1 dog.eat(dog, "狗粮")
TypeError: eat() takes 2 positional arguments but 3 were given
抛出了错误,说给了三个参数,实际只能给两个参数,所以在使用实例来调用eat函数时,会自动添加self参数也就是实例本身,而通过类调用eat函数时,需要指明是哪个实例,否则会出错
animal.eat("狗粮")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 animal.eat("狗粮")
TypeError: eat() missing 1 required positional argument: 'food'