Curriculum
__slots__
is a special attribute in Python that allows you to explicitly define the instance variables for a class. It’s a way to optimize memory usage and improve the performance of your code, especially when you’re creating many instances of the same class.
The __slots__
attribute is a list of strings that contains the names of the instance variables for the class. Here’s an example of how to use __slots__
:
class Person: __slots__ = ['name', 'age', 'address'] def __init__(self, name, age, address): self.name = name self.age = age self.address = address
In this example, the Person
class defines __slots__
to contain the names of the instance variables name
, age
, and address
. This means that instances of the Person
class can only have these instance variables.
Using __slots__
can provide some performance benefits, especially when you’re creating many instances of a class. Without __slots__
, each instance of a class would have a dictionary to store its instance variables, which can be memory-intensive. With __slots__
, each instance uses a fixed amount of memory, so creating many instances is more efficient.
However, there are some trade-offs to using __slots__
. One is that you can’t add new instance variables to instances of the class at runtime, because the class has already defined the instance variables that are allowed. Another is that you can’t use inheritance with __slots__
, because each subclass needs to define its own __slots__
attribute.
Here’s an example of how you can use the Person
class:
person = Person("John Smith", 30, "123 Main St") print(person.name) # "John Smith" print(person.age) # 30 print(person.address) # "123 Main St"
In this example, we create a new instance of the Person
class and set its name
, age
, and address
attributes. We can then access these attributes using dot notation, just like any other instance variables.