如何在不调用Python中的方法的情况下更改class中的属性值?
How to change the attribute value in class without calling the method in Python?
我在 Codecademy 上做这个 Pokemon 项目,它要求我做一些我完全无法想到的事情,因为我在 OOPS 和 python.[=16 上没有太多实践=]
如何设置 is_knocked_out = True
,而不调用我的实例的任何方法?我认为当宠物小精灵的生命值变为零并自动将其属性 is_knocked_out
更改为 True
时,我的代码应该会自动知道。
网上查了一下,没有找到确切的解决办法,可能跟装饰器有关。
谁能解释一下该怎么做,因为我想我可能在这里碰壁了。
到目前为止,我已经编写了以下代码:
class Pokemon:
def __init__(self,name,level,ptype,is_knocked_out= False):
self.name = name
self.level = level
self.type = ptype
self.max_health = level
self.curr_health = max_health
self.is_knocked_out = is_knocked_out
def lose_health(self,loss_amount):
self.curr_health -= loss_amount
print(f"{self.name} has now health of {self.curr_health}")
def regain_health(self,gain_amount):
self.curr_health += gain_amount
print(f"{self.name} has now health of {self.curr_health}")
#@property
def knock_out(self):
if self.curr_health <=0:
self.is_knocked_out = True
print(f"{self.name} has been knocked out")
一个好的方法是让 is_knocked_out
变成 property
这样它的值总是可以从 curr_health
:
计算出来
class Pokemon:
...
@property
def is_knocked_out(self):
return self.curr_health <= 0
我在 Codecademy 上做这个 Pokemon 项目,它要求我做一些我完全无法想到的事情,因为我在 OOPS 和 python.[=16 上没有太多实践=]
如何设置 is_knocked_out = True
,而不调用我的实例的任何方法?我认为当宠物小精灵的生命值变为零并自动将其属性 is_knocked_out
更改为 True
时,我的代码应该会自动知道。
网上查了一下,没有找到确切的解决办法,可能跟装饰器有关。
谁能解释一下该怎么做,因为我想我可能在这里碰壁了。
到目前为止,我已经编写了以下代码:
class Pokemon:
def __init__(self,name,level,ptype,is_knocked_out= False):
self.name = name
self.level = level
self.type = ptype
self.max_health = level
self.curr_health = max_health
self.is_knocked_out = is_knocked_out
def lose_health(self,loss_amount):
self.curr_health -= loss_amount
print(f"{self.name} has now health of {self.curr_health}")
def regain_health(self,gain_amount):
self.curr_health += gain_amount
print(f"{self.name} has now health of {self.curr_health}")
#@property
def knock_out(self):
if self.curr_health <=0:
self.is_knocked_out = True
print(f"{self.name} has been knocked out")
一个好的方法是让 is_knocked_out
变成 property
这样它的值总是可以从 curr_health
:
class Pokemon:
...
@property
def is_knocked_out(self):
return self.curr_health <= 0