gpt4 book ai didi

Python 静态类属性设置/获取

转载 作者:太空狗 更新时间:2023-10-29 21:22:41 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com