If I have this:
class foo(object):
@property
def bar(self):
return 0
f = foo()
How do I get a reference to f.bar without actually invoking the method, if this is even possible?
Edited to add: What I want to do is write a function that iterates over the members of f and does something with them (what is not important). Properties are tripping me up because merely naming them in getattr() invokes their __get__() method.
get_dict_attr(below) looks upattrin a given object’s__dict__, and returns the associated value if its there. Ifattris not a key in that__dict__, the object’s MRO’s__dict__s are searched. If the key is not found, anAttributeErroris raised.For example,
Note that this is very different than the normal rules of attribute lookup.
For one thing, data-descriptors in
obj.__class__.__dict__(descriptors with both__get__and__set__methods) normally have precedence over values inobj.__dict__. Inget_dict_attr,obj.__dict__has precedence.get_dict_attrdoes not try calling__getattr__.Finally,
get_dict_attrwill only work with objectsobjwhich are instances of new-style classes.Nevertheless, I hope it is of some help.
This references the property
bar:You see
baris a key inFoo.__dict__:All properties are descriptors, which implies it has a
__get__method:You can call the method by passing the object
f, and the class offas arguments:I am fond of the following diagram. Vertical lines show the relationship between an object and the object’s class.
When you have this situation:
f.barcausesb.__get__(f,Foo)to be called.This is explained in detail here.