__slots__
__dict__

  • By default, Python creates a __dict__ to save the attributes in the instance of class
  • Be able to create new attributes
  • class Vehicle(object):
    
        def __init__(self, brand, year):
            self._brand = brand
            self._year = year
    
        def __str__(self) -> str:
            return 'Brand: '+self._brand+' '+'Year: '+str(self._year)
    
    v1 = Vehicle('Subaru', 2022)
    v1.cylinder = 6
    v2 = Vehicle('Accord', 2016)
    
    print(v1.__dict__) # {'_brand': 'Subaru', '_year': 2022, 'cylinder': 6}
    print(v2.__dict__) # {'_brand': 'Accord', '_year': 2016}
            
    __slots__

  • More efficient in terms of memory space and speed of access
  • Prevents the creation of __dict__ and __weakref__ attributes
  • Any non-string iterable can be used for the __slots__ declaration, such as list, tuple, etc.
  • Adding a new attribute will raise an AttributeError
  • class Vehicle(object):
        __slots__ = ('brand', 'year')
    
        def __init__(self, brand, year):
            self.brand = brand
            self.year = year
    
        def __str__(self):
            return 'Brand: '+self.brand+' '+'Year: '+str(self.year)
    
    v1 = Vehicle('Subaru', 2022)
    v2 = Vehicle('Accord', 2016)
    
    print(v1.brand, v1.year)
    print(v2.brand, v2.year)
    
    # v1.cylinder = 6 # error
            
    Reference
  • Wiki