Use eval to set unknown property in Python

Posted by Mahi on Stack Overflow See other posts from Stack Overflow or by Mahi
Published on 2012-09-02T09:23:04Z Indexed on 2012/09/02 9:38 UTC
Read the original article Hit count: 309

Filed under:
|

I have an User class, that has multiple properties inside it, and I also have addPoint method for User class, which allows user to input points into any of it's properties. However, there can be up to like 500 properties, everyone can have different ones, etc. So it would be a pain in the ass to code every property with "if: - elif:". Now this is what I tried to do, to make it much easier and cleaner:

class User:
    def __init__(self):
        self.health = 0
        self.speed = 0

    def addPoint(self, property, amount):
        eval("self."+property) = eval("self."+property) + amount

And now when I'd do fe.

u = User()
u.addPoint("health", 5)

I would like it to do this: self.health = self.health + 5, and that's what I used the eval()s for. However, Python's just giving me error: can't assign to function call. I'm not trying to assign the eval() function call itself, I'm trying to assign the returned value from eval(), so how could I do this the easiest way?

© Stack Overflow or respective owner

Related posts about python

Related posts about eval