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
Also, you can easily add new attribute:
person.age = 25
print(person.age) # 25
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'
Top comments (0)