我制作了一个基本的只读描述符:
class ReadOnlyDescriptor:
def __init__(self):
pass
def __get__(self, obj, objtype=None):
return obj._something
def __set__(self, obj, value):
raise AttributeError("Cannot set this!")
def __delete__(self, obj):
raise AttributeError("Cannot delete this!")
class Object:
something = ReadOnlyDescriptor()
def __init__(self, something='abc'):
self._something=something
它适用于一个基本示例:
>>> a=Object()
>>> a.something
'abc'
>>> a.something='asdf'
AttributeError: Cannot update this!
>>> del a.something
AttributeError: Cannot delete this!
有没有办法使上述更通用?例如,而不是必须调用它obj._something
来__get__
动态调用它?换句话说(除了使用装饰器),执行上述操作的更通用方法是什么?