有没有办法在Python中创建类级别的只读属性?例如,如果我有课Foo,我想说:
x = Foo.CLASS_PROPERTY
Run Code Online (Sandbox Code Playgroud)
但是阻止任何人说:
Foo.CLASS_PROPERTY = y
Run Code Online (Sandbox Code Playgroud)
编辑: 我喜欢Alex Martelli解决方案的简单性,但不喜欢它需要的语法.他和~ututbu的答案都启发了以下解决方案,这更接近我所寻找的精神:
class const_value (object):
def __init__(self, value):
self.__value = value
def make_property(self):
return property(lambda cls: self.__value)
class ROType(type):
def __new__(mcl,classname,bases,classdict):
class UniqeROType (mcl):
pass
for attr, value in classdict.items():
if isinstance(value, const_value):
setattr(UniqeROType, attr, value.make_property())
classdict[attr] = value.make_property()
return type.__new__(UniqeROType,classname,bases,classdict)
class Foo(object):
__metaclass__=ROType
BAR = const_value(1)
BAZ = 2
class Bit(object):
__metaclass__=ROType
BOO = const_value(3)
BAN = 4
Run Code Online (Sandbox Code Playgroud)
现在,我得到:
Foo.BAR …Run Code Online (Sandbox Code Playgroud) python ×1