我正在寻找一种根据解析到方法的值来改变objects属性的方法。例如:
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)返回值自身.hp是指向而不是实际的自身.hp对象。你知道吗
我没有将属性作为dict的值,而是使用增加每个stat的方法
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
动态操作属性。比如说:例如:
或许更容易阅读:
注意,这比直接操作实例
__dict__
要好,后者将与property
对象之类的描述符分离。更不用说没有__dict__
的对象了,比如带有__slots__
的类型您可以使用
__setitem__
方法获得更简洁的解决方案:输出:
但是,也可以使用自定义方法来实现此策略:
输出:
相关问题 更多 >
编程相关推荐