Every class in python inherits from the class ‘object.’ I am wondering about the internal mechanism of the ‘object’ class implementation. Why cannot the ‘object’ class be assigned any user-attributes? I am convinced that it is related to memory-management but what if the user thinks of implementing the memory-management himself, why can’t he override ‘object’ class in python? This is based on my interest and want to know about which might not have any programmatic application but would be nice to know the internal feature of the language itself.
Share
If I had to derive the reasoning from first principles, I might think about it in terms of the
__slots__mechanism. Some kinds of classes only need a tiny number of attributes, and the set of attributes is always fixed for every instance, and so the flexibility of a “dict” like user attributes capability would be wasteful of cpu (looking up dynamically named attributes) and space (the overhead of an empty dict, small but non-zero), which can really add up to a lot of overhead if there are a large number of instances.of course this is exactly the problem the
__slots__mechanism solves. space is allocated on the object for the attributes defined in slots. if there’s a__dict__attribute, non-slot attributes can be found there, and if there’s no__dict__attribute, you get neither the dynamic attributes nor the cost of the unneeded dict object (which is an additional heap object other than the instance itself).As for why
objectitself does not have a slot for__dict__, well, even if a subclass indicated that they didn’t need the__dict__slot, if they inherit from a class that does, then the instance must still have a__dict__; ifobjecthad a__dict__then absolutely every class would also pay the price of having a__dict__, even if they didn’t need it.Instead; subclasses get
__dict__(and__weakref__, for analogous reasons) unless they themselves define a__slots__class attribute.And why would you need a plain-ol instance of
objectat all? Do you just need a bag of attributes? well then use adict. If you actually need an object of some kind with behaviors and attributes, then you are making a subclass anyways.About the only reason I can ever imagine using
object()instead of a subclass ofobject, is when the only feature of the instance that is of interest is its identity. This would come up when a function takes arguments, and for whichNoneor some other obvious sentinel value should be understood as distinct from the default:In which case you neither need nor particularly want attributes on the instance of
object,