-1

I understand that once we add __slots__ we are restricting the attributes that can be used in a class, although the primary purpose is to save memory of the created instance (by not storing it in the __dict__ )

But i don't fully understand how __slots__ behave when inherited.

class Vector(object): 
    __slots__ = ('name','age')
    def __init__(self):
        self.name = None
        self.age = None


class VectorSub(Vector):
    def __init__(self):
        self.name = None
        self.age = None
        self.c = None

a = Vector()  #  
b = VectorSub()
print dir(a)
# __slots__ defined and no __dict__ defined here, understandable

print dir(b) 
# Both __dict__ and __slot__ defined.
#So __slots__ is inherited for sure.


print a.__dict__ #AttributeError: has no attribute '__dict__, understandable
print b.__dict__ #{'c': None} ... How?
print b.name # Works, but why?  'name' not in b,__dict__

This is when i am confused. First off, if __slots__ is inherited, there shouldn't even be a __dict__ in "b" since the instance attributes cannot be stored in a dict - by the definition of slots. Also why is that name and age are not stored in b.__dict__ ?

SeasonalShot
  • 2,357
  • 3
  • 31
  • 49
  • 2
    Also this is covered in the docs for slots - "The action of a `__slots__` declaration is limited to the class where it is defined. As a result, subclasses will have a `__dict__` unless they also define `__slots__` (which must only contain names of any additional slots)." – pvg Sep 17 '17 at 01:53

1 Answers1

2

__slots__ not only saves memory, but also has faster access. (accessing tuple instead of a dict)

Taken from python's __slots__ doc:

The action of a slots declaration is limited to the class where it is defined. As a result, subclasses will have a dict unless they also define slots (which must only contain names of any additional slots).

So __slots__ is inherited, but a __dict__ attribute is also created for subclasses unless explicity define a __slots__ object in the subclass

There are few other notes worth mentioning, check slots doc

Chen A.
  • 10,140
  • 3
  • 42
  • 61