Memory Efficiency: __slots__ allows you to define a fixed set of attributes, eliminating the overhead of the default __dict__ storage.
Faster Attribute Access: By avoiding the dictionary lookup, attribute access can be faster.
Prevention of Dynamic Attributes: Helps prevent accidental creation of new attributes.
This technique is particularly beneficial when you're working with a large number of objects and need to save memory, such as in data-driven applications or high-performance computing.
import sysclassPerson:__slots__=['name','age']def__init__(self,name,age):self.name = nameself.age = ageperson =Person("John",30)print(sys.getsizeof(person))# Memory usage for an instance with __slots__# Without __slots__classPersonWithoutSlots:def__init__(self,name,age):self.name = nameself.age = ageperson_no_slots =PersonWithoutSlots("John",30)print(sys.getsizeof(person_no_slots))# Memory usage without __slots__
3. Preventing Dynamic Attribute Assignment
4. Using __slots__ with Inheritance
5. __slots__ in Combination with __dict__
6. Using __slots__ for Larger Classes
7. Dynamic Behavior with __slots__
8. Memory Usage Comparison Between __slots__ and Normal Classes
9. __slots__ with Class Variables
10. Trying to Add New Attributes to a Class with __slots__
class Vehicle:
__slots__ = ['make', 'model']
def __init__(self, make, model):
self.make = make
self.model = model
class Car(Vehicle):
__slots__ = ['year']
def __init__(self, make, model, year):
super().__init__(make, model)
self.year = year
car = Car("Toyota", "Corolla", 2020)
print(car.make, car.model, car.year) # Output: Toyota Corolla 2020
class Employee:
__slots__ = ['name', 'position']
def __init__(self, name, position):
self.name = name
self.position = position
emp = Employee("Alice", "Manager")
print(emp.__dict__) # Raises AttributeError since __dict__ is not available