Python创建只读包装类而不修改包装类

问题描述

我有一个如下所示的基类:

class Base:
    def __init__(self,prop):
        self.prop = prop

我想创建一个只读的包装类 ReadonlyWrapper,具有以下功能:

# Create instance using __init__ of base class.
readonly_instance = ReadonlyWrapper()

# I can access properties
prop = readonly_instance.prop

# This should raise a PermissionError
readonly_instance.prop = 23

更准确地说,我希望类的所有字段都是只读的,但只能在调用 __init__ 之后,否则无法在构造函数本身中构造类。 我知道可以使用属性装饰器来完成,但我不想将所有属性都转换为属性。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)