Python 中self 本质理解

之前一直自学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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值