How to prevent assigning attributes to an object that have not been specified in class definition?

纵饮孤独 提交于 2020-05-09 06:38:13

问题


I have defined a simple class. The suprising thing is: I can assign attributes that haven't been defined in the class definition.

  1. How is that possible?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!