我有一个User类,里面有多个属性,我也有User类的addPoint方法,允许用户将点输入到它的任何属性中。但是,最多可以有500个属性,每个人都可以拥有不同的属性等等。因此,使用“if: - elif:”对每个属性进行编码会很麻烦。现在这就是我试图做的事情,让它变得更容易和更清洁:
class User:
def __init__(self):
self.health = 0
self.speed = 0
def addPoint(self, property, amount):
eval("self."+property) = eval("self."+property) + amount
现在当我做fe。
u = User()
u.addPoint("health", 5)
我希望这样做:self.health = self.health + 5
,这就是我使用eval()
的原因。但是,Python只是给我错误:can't assign to function call
。我不是要尝试分配eval()
函数调用本身,我正在尝试从eval()
分配返回的值,那么我怎么能以最简单的方式执行此操作呢?
答案 0 :(得分:11)
答案 1 :(得分:2)
使用dictionary
代替eval()
:
class User:
def __init__(self):
self.health = 0
self.speed = 0
self.properties={}
def addPoint(self, property, amount):
self.properties[property] =self.properties.get(property,0)+amount
#self.properties.get(property,0) returns 0 if the property was not defined
答案 2 :(得分:2)
我不确定它是否是最佳解决方案,但您可以使用对象的 dict 属性:
def addPoint(self, property, amount):
self.__dict__[property] = amount
__dict__
属性存储对象的所有属性,您可以非常简洁的方式访问它们。
答案 3 :(得分:1)
使用Python标准库提供的函数settattr - 快速示例:
>>> class A:
... def __init__(self):
... setattr(self, "a", "b")
...
>>> A().a
'b'