gpt4 book ai didi

Python:类方法参数和类属性同名

转载 作者:行者123 更新时间:2023-11-30 22:16:48 26 4
gpt4 key购买 nike

我有一个类(class)作业。我的任务之一如下:

a.通过添加新属性 hunger 来增强 Tribute 类,该属性将描述对贡品的饥饿程度。 饥饿 的初始值应该是 0,因为所有贡品将在饱腹的情况下开始游戏。

b.创建一个方法 get_hunger(),该方法返回贡品的当前饥饿程度。

c.创建一个方法 add_hunger(hunger),它将向贡品的饥饿值添加饥饿。当贡品的饥饿值等于或大于100时,他/她将go_to_heaven()。 (仅供引用 go_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?

最佳答案

变量进行赋值。这就是 Python 的工作原理。变量是对内存中对象的引用。

函数调用返回对象,并且您不能分配给对象。

<小时/>

我建议使用 setter 方法来处理抽象的另一面。

class Tribute(Person):
...

def get_hunger(self):
return self.hunger

def set_hunger(self, hunger):
self.hunger = hunger

def add_hunger(self,hunger):
self.set_hunger(self.get_hunger() + hunger)
if self.get_hunger() >= 100:
self.go_to_heaven()

关于Python:类方法参数和类属性同名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49848347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com