This naive class attempts to mimic the attribute access of basic python objects. dict
and cls
explicitly stores the attributes and the class. The effect is that accessing .x
of an instance will return dict[x]
, or if that fails, cls.x
. Just like normal objects.
class Instance(object):
__slots__ = ["dict", "cls"]
def __getattribute__(self, key):
try:
return self.dict[key]
except KeyError:
return getattr(self.cls, key)
def __setattr__(self, key, value):
if key == "__class__":
self.cls = value
else:
self.dict[key] = value
But it's nowhere near as simple as that. One obvious issue is the complete disregard for descriptors. Just imagine that cls
has properties. Doing Instance.some_property = 10
should access the property as defined in cls
, but will instead happily set some_property
as an attribute in dict
.
Then there is the issue of binding methods of cls
to instances of Instance
, and possibly more that I don't even know.
There seem to be a lot of details to get the above class to function as close to python objects as possible, and the docs for descriptors I've read so far hasn't made it clear how to get, simply put, everything right.
What I am asking for is a reference for implementing a complete replacement for python's attribute access. That is, the above class, but correct.