How to use __slots__ in Python class

Since Python is a dynamic language, there is no need to declare variables, and instance variables can be created dynamically.

class User:
    pass


user1 = User()
user1.username = 'kaito'

Use \ _ \ _ slots \ _ \ _ </ code> to restrict the creation of instance variables without permission.

class User:
    __slots__ = ('username', 'age')

user1 = User()
user1.username = 'kaito'
user1.password = 'aaa'

You can see the error.

      4 user1 = User()
      5 user1.username = 'kaito'
----> 6 user1.password = 'aaa'

AttributeError: 'User' object has no attribute 'password'

Also, Python stores instance variables in a dictionary, but by defining \ _ \ _ slots \ _ \ _ </ code>, tuples are used instead of dictionaries, which saves memory.

Recommended Posts