【问题标题】:Python static class property set/get [duplicate]Python静态类属性设置/获取[重复]
【发布时间】:2012-11-22 20:44:18
【问题描述】:

可能重复:
Private functions / Variables enforcement in python

可以创建一个等效于以下具有两个静态属性的类,一个是只读的,另一个是 Python 中的读写?

class Foo
{
    private static string _rdy = "RO";
    public static string rd
    {
        get { return _rd; }
    }

    private static string _rw = "RW";
    public static string rw
    {
        get { return _rw ; }
        set { _rw = value; }
    }
}

我知道read-only class properties 在 Python 中是可能的,但是我还没有看到 Python 中任何读写类属性的示例。可能吗?基本上我想要:

class classproperty(object):

    def __init__(self, getter
            #, setter
        ):
        self.getter = getter
    #    self.setter = setter

    def __get__(self, instance, owner):
        return self.getter(owner)

    # Could there be a __set__ here?
    #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    #def __set__(self, instance, owner, value):
    #    self.setter(owner, value)
    #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

class Foo(object):

    _ro = "RO"
    _rw = "RW"

    @classproperty
    def ro(cls):
        return cls._ro

    # How would you this?
    #vvvvvvvvvvvvvvvvvvvv
    #@classproperty.setter
    #^^^^^^^^^^^^^^^^^^^^
    #def rw(cls, value):
    #    cls._rw, value

# This is what I need
>>> Foo.ro
RO
>>> Foo.ro = 'X'     # Hypothetical Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class 'Foo' attribute 'ro' is not writable!
>>> Foo.rw
RW
>>> Foo.rw = 'NEW'
>>> Foo.rw
NEW

【问题讨论】:

    标签: python class properties


    【解决方案1】:

    我认为您想使用内置的property()http://docs.python.org/2/library/functions.html#property

    虽然传统上它用于实例,但我认为您可以在元类上使用它来实现您想要的。

    class MetaFoo(type):
        _ro = "RO"
        _rw = "RW"
    
        def _get_ro(self):
            return self._ro
        def _get_rw(self):
            return self._rw
        def _set_ro(self, value):
            raise AttributeError("class 'Foo' attribute 'ro' is not writable!")
        def _set_rw(self, value):
            self._rw = value
        ro = property(_get_ro, _set_ro)
        rw = property(_get_rw, _set_rw)
    
    
    class Foo(object):
        __metaclass__=MetaFoo
    
    
    assert Foo.rw == "RW"
    Foo.rw = 'NEW'
    assert Foo.rw == "NEW"
    
    assert Foo.ro == "RO"
    
    try:
        Foo.ro = 'X'
    except Exception as e:
        assert str(e) == "class 'Foo' attribute 'ro' is not writable!", str(e)
        assert type(e) == AttributeError
    

    【讨论】:

    • 太好了。这是我见过的最简单的答案。
    • 当有__metaclasses__定义时,如何将文档字符串添加到这些类属性中?
    • property()有两种使用方式。我展示并作为装饰者。装饰器形式保留文档字符串。我展示的方式是,文档字符串是第四个参数,而第三个参数是属性的删除方法。再次,请参阅我包含的 python 文档链接。
    • 太棒了。这也适用于 @property 装饰器。元类中的“self”可能应该是“cls”(只是为了约定)。
    猜你喜欢
    • 2014-12-07
    • 2020-05-23
    • 1970-01-01
    • 2014-04-04
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多