Reputation: 794
I am trying to call a property from within its class and get the value. I understand that properties are A.foo.__get__(a)
, but since the properties are within the instance of the class I am not sure what my a
would be. Currently, my attempts return the object and location. This makes sense, but how would I proceed so that it instead returns the value of the property?
class Burgers(object):
def __init__(self):
self.burger1 = self.make_burger_dict('mc')
self.burger2 = self.make_burger_dict('bk')
print self.burger1
# prints {1: <property object at 0x10d51b7e0>, 2: <property object at 0x10d51b7e0>}
# what I want {1: 'Big Mac', 2: 'Big Mac'}
@property
def bk(self):
return "Whopper"
@property
def mc(self):
return "Big Mac"
def make_burger_dict(self, key):
return {
1: vars(Burgers)[key],
2: getattr(Burgers, key),
}
x = Burgers()
I tried 3: eval("self." + key)
in the make_burger_dict method, and that creates the desired outcome. However, I've heard to avoid eval
, so is there away to do this without using it?
Upvotes: 0
Views: 76
Reputation: 37509
I think this is what you want. You shouldn't have to deal with the __get__
nonsense. That's the whole point of creating a descriptor on a class; python handles it automagically.
def make_burger_dict(self, key):
val = getattr(self, key)
return {1: val, 2: val}
Upvotes: 3