我已经做了一个基本的只读描述符:
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__
来调用它吗?换句话说(除了使用装饰器之外),执行上述操作的更通用方法是什么?