我有一个课堂作业。我的任务之一是:
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?