slots — restriction of instance attributes.
1class User:2 __slots__ = ("name", "age")34 def __init__(self, name, age):5 self.name = name6 self.age = age78user = User("Alice", 25)9# user.email = "a@b.com" # Error! Not in __slots__1011# Memory savings12import sys1314class WithSlots:15 __slots__ = ("x", "y")1617class WithoutSlots:18 pass1920a = WithSlots()21b = WithoutSlots()22print(sys.getsizeof(a)) # Less!23print(sys.getsizeof(b)) # More!2425# Inheritance26class Admin(User):27 __slots__ = ("role",) # + parent slots
Advantages:
Disadvantages: