DEV Community

Chris Chen
Chris Chen

Posted on

Introducing to Python __slots__ method

Just came across this special method __slots__
According to the Document, __slots__ allow us to explicitly declare data members (like properties) and deny the creation of __dict__ and __weakref__ (unless explicitly declared in __slots__ or available in a parent), which means we can use slots to avoid attributes to be dynamically created.


Example

When you create a class, you can access its attributes like this:

class Person:
    def __init__(self,
                 first_name,
                 last_name):
        self.first_name = first_name
        self.last_name = last_name

person = Person('Chris', 'Ryan')
print(person.first_name) # Chris
print(person.last_name) # Chen
Enter fullscreen mode Exit fullscreen mode

Also, you can easily add new attribute:

person.age = 25
print(person.age) # 25
Enter fullscreen mode Exit fullscreen mode

BUT, what if we want to prevent the attributes from being dynamically created?
In this case, I only want my Person class to have first_name and last_name, two attributes.
Try this:

class Person:
    __slots__ = ['first_name', 'last_name']

    def __init__(self,
                 first_name,
                 last_name):
        self.first_name = first_name
        self.last_name = last_name

person = Person('Chris', 'Ryan')
person.age = 25
# AttributeError: 'Person' object has no attribute 'age'

Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Top comments (0)