我正在寻找一种方法来根据解析为方法的值来更改对象属性。例如:
class Character(object):
def __init__(self, hp, mp, st, ag):
self.hp = hp
self.mp = mp
self.st = st
self.ag = ag
def increase_stat(self, stat, value):
''' Increase one of the attributes
(hp, mp, st, ag) by a given value.
'''
stat_dict = {'hp': self.hp,
'mp': self.mp,
'st': self.st,
'ag': self.ag}
stat_attr = stat_dict.get(stat)
# below should be equivalent to self.hp += value
stat_attr += value
hero = Character(hp=10, mp=4, st=3, ag=2)
hero.increase_stat(stat='hp', value=2)
# this should increase the hp by 2
print(hero.hp == 12)
我知道这不起作用,因为 stat_dict.get(stat) 返回 self.hp 指向的值而不是实际的 self.hp 对象。
当前解决方案
我没有将属性作为字典的值,而是使用增加每个单独统计数据的方法。
class Character(object):
def __init__(self, hp, mp, st, ag):
self.hp = hp
self.mp = mp
self.st = st
self.ag = ag
def increase_stat(self, stat, value):
''' Increase one of the attributes
(hp, mp, st, ag) by a given value.
'''
stat_method_dict = {'hp': self._increase_hp,
'mp': self._increase_mp,
'st': self._increase_st,
'ag': self._increase_ag}
alter_stat_method = stat_method_dict.get(stat)
alter_stat_method(value)
def _increase_hp(self, value):
self.hp += value
def _increase_mp(self, value):
self.mp += value
def _increase_st(self, value):
self.st += value
def _increase_ag(self, value):
self.ag = value
hero = Character(hp=10, mp=4, st=3, ag=2)
hero.increase_stat(stat='hp', value=2)
# this should increase the hp by 2
print(hero.hp == 12)
我的问题是它是重复的,如果我决定向类添加更多属性/统计信息,那么这只会增加重复方法的数量。我想知道是否有比我上面提供的更好的解决方案?
解决方案
现在看来非常明显。谢谢大家。
class Character(object):
def __init__(self, hp, mp, st, ag):
self.hp = hp
self.mp = mp
self.st = st
self.ag = ag
def increase_stat(self, stat, value):
''' Increase one of the attributes
(hp, mp, st, ag) by a given value.
'''
current = getattr(self, stat)
setattr(self, stat, current+value)
最佳答案
你的统计字典确实没有任何作用。使用 getattr
和 setattr
动态操作属性。所以,类似于:
def increase_stat(self, stat, value):
setattr(self, stat, value + getattr(self, stat))
所以,例如:
In [30]: class Dummy:
...: def __init__(self):
...: self.intelligence = 0
...: self.strength = 10
...: self.hp = 100
...: def increase_stat(self, stat, value):
...: setattr(self, stat, value + getattr(self, stat))
...:
In [31]: d = Dummy()
In [32]: d.strength
Out[32]: 10
In [33]: d.increase_stat('strength', 10)
In [34]: d.strength
Out[34]: 20
也许更容易阅读:
def increase_stat(self, stat, value):
current = getattr(self, stat)
setattr(self, stat, current + value)
请注意,这比直接操作实例 __dict__
更好,后者会因 property
对象等描述符而中断。更不用说没有 __dict__
的对象,例如带有 __slots__
关于python - 如何获取对象属性的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079461/