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 = ageHere, setting
__slots__as["name", "age"]means that ourDogobject can only have these 2 attributes.dog = Dog("rocky", 5) # ok dog.name = "fifi" # ok dog.age = 6 # ok dog.breed = "mongrel" # errorHere, we get an error when we try to set the
breedattribute of theDogobject, as onlynameandageare allowed based on__slots__. This error won’t happen if we didn’t specifically define the__slots__attribute.
Leave a comment