如何在Python中保护类属性?

用户2923089

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

class foo(object):
     pass

x=foo()
x.someRandomAttr=3.14
马丁·彼得斯(Martijn Pieters)

如果您想要一个不可变的对象,请使用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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章