What Is The Lookup Procedure When Setting An Attribute From A Class Or From An Instance?
Solution 1:
For x.y = z, Python looks up x.__setattr__ in a way that bypasses __getattribute__, __getattr__, and x's own __dict__, then calls x.__setattr__('y', z).
A custom __setattr__ can do whatever the heck it wants, but here's the default:
Search
type(x).__mro__for a__dict__entry matching the attribute name.If this search finds a descriptor
descrwith a__set__method (looking up__set__the same way we looked up__setattr__), calldescr.__set__(x, z).2.a. In the highly unusual case that the search finds a descriptor with
__delete__but no__set__, raise anAttributeError.Otherwise, set
x.__dict__['y'] = z, or raise anAttributeErrorifxhas no__dict__. (This uses the "real"__dict__, bypassing things likemappingproxy.)
This applies to both types and other objects, with the caveats that type.__setattr__ will refuse to set attributes of a class written in C, and type.__setattr__ does some extra internal maintenance you'll never need to worry about unless you do something crazy and unsupported to bypass it.
Post a Comment for "What Is The Lookup Procedure When Setting An Attribute From A Class Or From An Instance?"