Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
In Python, __slots__
is an attribute you can add to a class to define a fixed set of attributes for its instances. By doing so, you can save memory and potentially improve performance, as instances will not use a dictionary to store their attributes. Here's a step-by-step tutorial on using __slots__
in Python:
__slots__
:First, let's create a simple class without __slots__
. In this example, we create a Person
class with name
and age
attributes:
class Person: def __init__(self, name, age): self.name = name self.age = age
By default, instances of the Person
class will use a dictionary (__dict__
) to store their attributes, which can consume more memory:
person1 = Person("Alice", 30) print(person1.__dict__) # Output: {'name': 'Alice', 'age': 30}
__slots__
:To save memory and optimize attribute storage, you can add a __slots__
attribute to the class. __slots__
should be a sequence (e.g., tuple or list) containing the names of the instance attributes:
class Person: __slots__ = ('name', 'age') def __init__(self, name, age): self.name = name self.age = age
Now, instances of the Person
class will use a more memory-efficient storage for their attributes, without a dictionary:
person2 = Person("Bob", 25) print(person2.__dict__) # Raises AttributeError: 'Person' object has no attribute '__dict__'
__slots__
:You can access and modify the attributes of instances with __slots__
in the same way as instances without __slots__
:
print(person2.name) # Output: Bob print(person2.age) # Output: 25 person2.age = 26 print(person2.age) # Output: 26
__slots__
:__slots__
does not work with instances that need to have dynamic attributes (i.e., attributes not defined in __slots__
).__slots__
is subclassed, the subclass will use a dictionary for its attributes unless it also defines __slots__
.__slots__
can make your code less flexible and harder to work with in some cases, as you cannot add new attributes to instances after they are created.This tutorial covered the basics of using __slots__
in Python to define a fixed set of attributes for class instances and optimize memory usage. While __slots__
can be helpful in certain situations, you should carefully consider its limitations and use it only when the memory optimization benefits outweigh the potential drawbacks.
How to use slots to restrict attributes in Python:
__slots__
attribute in the class.class RestrictedClass: __slots__ = ('attribute1', 'attribute2') # Using slots to restrict attributes obj = RestrictedClass() obj.attribute1 = 42 obj.attribute2 = "Hello" # obj.attribute3 = "Error" # Raises AttributeError
Preventing dynamic attribute creation with slots:
class NoDynamicAttributes: __slots__ = ('attribute1', 'attribute2') # Preventing dynamic attribute creation with slots obj = NoDynamicAttributes() obj.attribute1 = 42 obj.attribute2 = "Hello" # obj.attribute3 = "Error" # Raises AttributeError
Defining and modifying slots in Python classes:
__slots__
attribute, which can be a tuple or a list of attribute names. It can be modified to add or remove slots dynamically.class DynamicSlotsClass: __slots__ = ('attribute1', 'attribute2') # Defining and modifying slots obj = DynamicSlotsClass() obj.attribute1 = 42 obj.attribute2 = "Hello" # Adding a new slot dynamically DynamicSlotsClass.__slots__ += ('attribute3',) obj.attribute3 = True
Inheritance and slots in Python:
class ParentClass: __slots__ = ('parent_attribute',) class ChildClass(ParentClass): __slots__ = ('child_attribute',) # Inheritance and slots obj = ChildClass() obj.parent_attribute = "Parent" obj.child_attribute = "Child"
Validating attribute names with slots:
class ValidatedClass: __slots__ = ('attribute1', 'attribute2') # Validating attribute names with slots obj = ValidatedClass() obj.attribute1 = 42 obj.attribute2 = "Hello" # obj.attribute3 = "Error" # Raises AttributeError