python 类各方法参数_Python:类方法参数和类attribu的名称相同

我有一个课堂作业。我的任务之一是:

a.通过添加一个新属性hunger来扩充属性类,该属性将描述

对贡品的渴望程度。hunger的初始值应为0

祭品将以饱腹开始比赛。在

b.创建一个方法,get_hunger(),该方法返回属性的当前饥饿级别。在

c.创建一个方法add_hunger(hunger),该方法将为属性的

饥饿。当对贡品的渴求达到或超过100时,他/她就会

go_to_heaven()。(FYIgo_to_heaven()先前由其他父类定义)1)I wrote the following code, and when I tried running it I keep getting syntax error highlighted on the indentation right before self.get_hunger()+=hunger. May I know the reason for the syntax error since .get_hunger() is essentially self.hunger. self.get_hunger()=0 will work for other codes following this task but I don’t understand why self.get_hunger()+=hunger wont work. My lecturer stresses on not breaking the underlying layer of abstraction, which is why I would use the method .get_hunger() over attribute hunger, especially if I needed to get hunger value from instances of future child classes of Tribute, not sure if this concept is also embraced in practical situations.class Tribute(Person):

def __init__(self, name, health):

super().__init__(name, health, -1)

self.hunger=0

def get_hunger(self):

return self.hunger

def add_hunger(self,hunger):

self.get_hunger()+=hunger #dk why can't assign to function call

if self.get_hunger()>=100:

self.go_to_heaven()2)I also tried writing self.hunger+=hungerinstead of self.get_hunger()+=hunger to get past the syntax error and it works.However, I don’t find it intuitive why when defining a class method, and when I face a scenario where the name of the method parameter and the name of the class attribute is the same, the parameter will not overwrite the attribute in the form of hunger. Can anyone reason with me?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值