Force python class to accept only certain attributes
We can force Python classes to accept only certain attributes. We can achieve this using the slots special attribute
class Dog(): __slots__ = ["name", "age"] def __init__(self, name, age): self.name = name self.age = age
Here, setting
__slots__
as["name", "age"]
means that ourDog
object can only have these 2 attributes.dog = Dog("rocky", 5) # ok dog.name = "fifi" # ok dog.age = 6 # ok dog.breed = "mongrel" # error
Here, we get an error when we try to set the
breed
attribute of theDog
object, as onlyname
andage
are allowed based on__slots__
. This error won’t happen if we didn’t specifically define the__slots__
attribute.
Leave a comment