Question

I bumped into the following last night and I'm still at a loss as to explain it:

class Foo(object):
    @property
    def dave(self):
        vars(self)['dave'] = 1
        return 2

f = Foo()
print f.dave
print f.dave

Running this code produces:

2
2

The question is why? My understanding of attribute access is that the instance dictionary is checked before the class dictionary, and the dictionary of any bases, however as seen above the instance dictionary doesn't appear to be getting checked before the descriptor is found in the class dictionary.

Was it helpful?

Solution

My understanding of attribute access is that the instance dictionary is checked before the class dictionary, and the dictionary of any bases

Data descriptors are an exception:

For instance bindings, the precedence of descriptor invocation depends on the which descriptor methods are defined. Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method. Data descriptors always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances.

http://docs.python.org/reference/datamodel.html#invoking-descriptors

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top