如何在Python中保护类属性?

时间:2013-10-26 14:06:10

标签: python oop

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

class foo(object):
     pass

x=foo()
x.someRandomAttr=3.14

2 个答案:

答案 0 :(得分:4)

如果您想要一个不可变对象,请使用collections.namedtuple() factory为您创建一个类:

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

答案 1 :(得分: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

即使Foo的子类也会引发同样的错误:

>>> 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