As a dynamic language, Python has more flexibility than other languages such as Java or C++. When it comes to OOP, a big advantage is that we can add extra attributes and methods into a Python class at runtime.
For example, the following code defines a class named Author. We can add an extra attribute age into an instance of this class:
However, in some cases, allowing the users of a class to add additional attributes at runtime is not a safe choice. Especially when the user has no idea about the implementation of the class. Not to mention that it may invoke out-of-memory issues if a user adds too many extra attributes.
Therefore, Python provides a special built-in attribute — __slots__ .
We can add it to a class definition and specify the names of all valid attributes of the class. It works as a whitelist.
Now, let’s change the previous program a bit: