问题
I have defined a simple class. The suprising thing is: I can assign attributes that haven't been defined in the class definition.
- How is that possible?
- How can I prevent this from happening?
See here, what I mean, this is my simple class:
class Dog:
def __init__(self,name):
self.name=name
Of course I can now instanciate an object: dog = Dog('Fido')
Printing Print(dog.name) yields 'Fido'.
But now I just can assign to my object dog new attributes though I haven't included them in the class definition.
For example: dog.mood="happy" works. When I print Print(dog.mood), I get 'happy', that means it works. Why is this possible and how can I prevent assigning values to attributes like "mood" even though I haven't defined them in my class definition of dog?
回答1:
By default, a user-defined class allows you to assign attributes dynamically. One way to prevent this is to use __slots__ in your class:
>>> class Dog:
... __slots__ = ('name',)
... def __init__(self, name):
... self.name = name
...
>>> dog = Dog('Fido')
>>> print(dog.name)
Fido
>>> dog.mood = 'happy'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Dog' object has no attribute 'mood'
__slots__ makes it so your instance no longer carries around a __dict__ for its namespace, which would be a literal python dict object. This makes user-defined objects rather bloated by default, so this makes your objects use less memory, and will optimize attribute access as well (removing the need for a hash-based lookup).
Here is the link to some documentation
来源:https://stackoverflow.com/questions/60626609/how-to-prevent-assigning-attributes-to-an-object-that-have-not-been-specified-in