问题描述
我已经定义了一个简单的类。令人惊讶的是:我可以分配在类定义中未定义的属性。
- 这怎么可能?
- 如何防止这种情况发生?
在这里,我的意思是这是我的简单课程:
类狗:
def __init __(self,name):
self.name = name
我现在当然可以实例化一个对象: dog = Dog('Fido')
打印 Print(dog.name)
产生'Fido'
。
但是,尽管我没有在类定义中包含新属性,但现在我可以将其分配给我的对象dog。
例如: dog.mood = happy
有效。当我打印 Print(dog.mood)
时,我得到'happy'
,这意味着它可行。为什么这可能?为什么我防止为情绪之类的属性分配值,即使我没有在dog的类定义中定义它们呢?
默认情况下,用户定义的类可让您动态分配属性。防止这种情况的一种方法是在您的班级中使用 __ slots __
:
>>> class Dog:
... __slots__ =('name',)
... def __init __(self,name):
... self.name =名称
。 ..
>> dog = Dog(’Fido’)
>>> print(dog.name)
Fido
>> dog.mood = happy
追溯(最近一次通话最近):
文件< stdin>,在< module>中的第1行
AttributeError:狗对象没有属性心情
__ slots __
使其成为命名空间,因此您的实例不再为其命名空间携带 __ dict __
了,这将是字面的python dict
对象。默认情况下,这会使用户定义的对象变得肿,因此使您的对象使用的内存更少,并且还将优化属性访问(无需进行基于哈希的查找)。
这是
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?
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
这篇关于如何防止将属性分配给未在类定义中指定的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!