4

我有一个 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()s 的目的。但是,Python 只是给了我错误:can't assign to function call. 我不是试图分配eval()函数调用本身,而是试图从 分配返回的值eval(),那么我怎么能以最简单的方式做到这一点呢?

4

4 回答 4

12

不要使用eval(),使用setattr()andgetattr()代替:

setattr(self, property, getattr(self, property) + amount)
于 2012-09-02T09:27:09.590 回答
2

使用 adictionary而不是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
于 2012-09-02T09:27:25.160 回答
2

我不确定这是否是最佳解决方案,但您可以像这样使用对象的dict属性:

def addPoint(self, property, amount):
    self.__dict__[property] = amount

__dict__属性存储对象的所有属性,您可以非常简洁地访问它们。

于 2012-09-02T09:33:38.660 回答
1

使用 Python 标准库提供的函数 settattr - 快速示例:

>>> class A:
...     def __init__(self):
...         setattr(self, "a", "b")
... 
>>> A().a
'b'
于 2012-09-02T09:29:31.557 回答