制作只读描述符

2024-10-03 15:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个基本的只读描述符:

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!

有没有办法使上述内容更通用?例如,不必在__get__中调用obj._something,它就可以动态地调用它?换句话说(除了使用decorator),做上述工作的一般方法是什么


Tags: selfobjgetobjectinitdefthisdelete