0

如何保护类不以这种方式添加属性:

class foo(object):
     pass

x=foo()
x.someRandomAttr=3.14
4

2 回答 2

4

如果您想要一个不可变对象,请使用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
于 2013-10-26T14:14:27.933 回答
3

覆盖__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
于 2013-10-26T14:13:02.133 回答