15. Slot Classes
class Point:
__slots__ = ['x', 'y'] # Define allowed attributes
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.x, p.y) # Output: 1 2import sys
class Person:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
print(sys.getsizeof(person)) # Memory usage for an instance with __slots__
# Without __slots__
class PersonWithoutSlots:
def __init__(self, name, age):
self.name = name
self.age = age
person_no_slots = PersonWithoutSlots("John", 30)
print(sys.getsizeof(person_no_slots)) # Memory usage without __slots__Last updated