[英]How can I change one variable in class every time when another changes? Python
Here is my code and I want the damage to change every time the level changes这是我的代码,我希望每次级别更改时都会更改损坏
class Item:
__ids = count(0)
def __init__(self):
self.name = 'Nothing'
self.id = next(self.__ids)
self.level = 1
class Weapon(Item):
def __init__(self):
super().__init__()
self.damage = 1
def setDamage(self):
self.damage = (self.level * 2.25, self.level * 2.25 + self.level // (self.level / 2))
@property
def damage(self):
return self.damage
@damage.setter
def damage(self):
self.setDamage()
Ignore the incorrectness of the code if it does not interfere with the question, I am new in python代码的不正确如果不干扰问题就忽略,我是python的新手
There appears to be no reason to set a weapon's damage at all;似乎根本没有理由设定武器的伤害; it is entirely a function of the weapon's level.
完全是武器级别的function。
# Irrelevant code removed
class Item:
def __init__(self):
self.level = 1
class Weapon(Item):
@property
def damage(self):
base = self.level * 2.25
return (base, base + self.level // (self.level / 2))
something like this could do what you want.像这样的东西可以做你想做的事。 I'm not sure how you want the damage to scale with the level.
我不确定你希望伤害如何随着水平的增加而变化。 I have it set to always be 2.25x whatever the level is.
无论级别是多少,我都将其设置为始终为 2.25 倍。
class Weapon(Item):
def __init__(self):
super().__init__()
@property
def damage(self):
return self.level * 2.25
I think a levelUp() function might be a better idea than changing the level externally at all.我认为 levelUp() function 可能比从外部更改级别更好。
def levelUp():
self.level+=1
self.setDamage()
#any other level up stuff like a shinier picture
Currently to level something up you have to find its current level, which is tiresome, and find some way to automatically update the damage when level is changed, which would be an non-obvious side-effect of this assignment.目前要升级某些东西,你必须找到它的当前等级,这很烦人,并找到一些方法来在等级改变时自动更新伤害,这将是这个任务的一个不明显的副作用。
sword.level = sword.level + 1
With a levelUp
function you can just do使用
levelUp
function 你可以做到
sword.levelUp()
Without having to check its current state at all.根本无需检查其当前的 state。 This also allows you to handle levelling up differently for each item type (what if there isn't a simple mathematical relationship between damage and level for some other weapon, or you want to limit it at some upper limit etc.)
这还允许您为每种物品类型处理不同的升级(如果其他武器的伤害和等级之间没有简单的数学关系,或者您想将其限制在某个上限等)
You can always safely just do你总是可以安全地做
for item in items:
item.levelup()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.