如何保护类不以这种方式添加属性:
class foo(object):
pass
x=foo()
x.someRandomAttr=3.14
如果您想要一个不可变对象,请使用collections.namedtuple()
工厂为您创建一个类:
from collections import namedtuple
foo = namedtuple('foo', ('bar', 'baz'))
演示:
>>> from collections import namedtuple
>>> foo = namedtuple('foo', ('bar', 'baz'))
>>> f = foo(42, 38)
>>> f.someattribute = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'foo' object has no attribute 'someattribute'
>>> f.bar
42
请注意,整个对象是不可变的;你也不能f.bar
事后改变:
>>> f.bar = 43
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
覆盖__setattr__
方法:
>>> class Foo(object):
def __setattr__(self, var, val):
raise TypeError("You're not allowed to do this")
...
>>> Foo().x = 1
Traceback (most recent call last):
File "<ipython-input-31-be77d2b3299a>", line 1, in <module>
Foo().x = 1
File "<ipython-input-30-cb58a6713335>", line 3, in __setattr__
raise TypeError("You're not allowed to do this")
TypeError: You're not allowed to do this
EvenFoo
的子类会引发同样的错误:
>>> class Bar(Foo):
pass
...
>>> Bar().x = 1
Traceback (most recent call last):
File "<ipython-input-35-35cd058c173b>", line 1, in <module>
Bar().x = 1
File "<ipython-input-30-cb58a6713335>", line 3, in __setattr__
raise TypeError("You're not allowed to do this")
TypeError: You're not allowed to do this