python:不可变的私有类变量?

2024-01-08

有没有办法把这个Java代码翻译成Python?

class Foo
{
    final static private List<Thingy> thingies = 
       ImmutableList.of(thing1, thing2, thing3);
}

e.g. thingies是一个不可变的私有列表Thingy属于的对象Foo类而不是它的实例。

我知道如何从这个问题定义静态类变量Python 中的静态类变量 https://stackoverflow.com/questions/68645/static-class-variables-in-python但我不知道如何使它们不可变和私有。


在 Python 中,约定是使用_属性名称前缀的含义protected and a __前缀表示意思private。这不是由语言强制执行的;而是由语言强制执行的。程序员应该知道不要编写依赖于非公开数据的代码。

If you really wanted to enforce immutability, you could use a metaclass[docs http://docs.python.org/reference/datamodel.html#customizing-class-creation] (the class of a class). Just modify __setattr__ and __delattr__ to raise exceptions when someone attempts to modify it, and make it a tuple (an immutable list) [docs http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences].

class FooMeta(type):
    """A type whose .thingies attribute can't be modified."""

    def __setattr__(cls, name, value):
        if name == "thingies":
            raise AttributeError("Cannot modify .thingies")
        else:
            return type.__setattr__(cls, name, value)

    def __delattr__(cls, name):
        if name == "thingies":
            raise AttributeError("Cannot delete .thingies")
        else:
            return type.__delattr__(cls, name)

thing1, thing2, thing3 = range(3)

class Foo(object):
    __metaclass__ = FooMeta
    thingies = (thing1, thing2, thing3)
    other = [1, 2, 3]

Examples

print Foo.thingies # prints "(0, 1, 2)"
Foo.thingies = (1, 2) # raises an AttributeError
del Foo.thingies # raise an AttributeError
Foo.other = Foo.other + [4] # no exception
print Foo.other # prints "[1, 2, 3, 4]"

从技术上讲,仍然可以通过类的内部来修改它们.__dict__属性,但这应该足以阻止大多数用户,完全保护 Python 对象是非常困难的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python:不可变的私有类变量? 的相关文章

随机推荐