-1

From https://stackoverflow.com/a/44880260

object() doesn't support instance attributes because it is the base for all custom Python classes, which must support not having a __dict__ attribute when defining slots instead.

Does "it" in "it is the base for all custom Python classes" mean class object or its instance object()? I guess class object?

Since it is object instead of object() which is the base for all custom Python classes, is it also object instead of object() which must support the instances of some custom Python classes not having a __dict__ attribute when the classes defining __slots__ instead?

So how shall I understand that object() not having __dict__ is to support the instances of some custom Python classes not having a __dict__ attribute when the classes defining __slots__ instead?

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590

2 Answers2

2

Per the "Notes on using __slots__":

When inheriting from a class without __slots__, the __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.

The wording is a little imprecise; technically, since all classes inherit from object (which lacks __slots__), that would imply that instances would all have __dict__, but what they really mean to say is that if __dict__ is not suppressed on instances at every level of the inheritance tree (by failing to provide __dict__ for built-in types like object, or suppressing it with __slots__ on user-defined classes), then a __dict__ will exist for instances of the first class in the tree that fails to suppress __dict__, and for all of its subclasses, even if they try to use __slots__ to suppress __dict__.

Basically, if object instances had __dict__, all instances of all classes would have it as well; by suppressing it on object, the subclasses of object (read: All classes) retain the option to have __dict__ or not.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Yes, your understanding is correct. Subclasses of object may not want a __dict__ for their instances, but if object instances had one, their subclass instances will have one too.

The issue is mostly that object is the parent class of all other classes in Python. If it was designed so that its instances had a __dict__, that __dict__ would be inherited by all instances of all classes.

Blckknght
  • 100,903
  • 11
  • 120
  • 169