Python创建只读包装类而不修改包装类 [英] Python creating a readonly wrapper class without modifying wrapped class

查看:30
本文介绍了Python创建只读包装类而不修改包装类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a base class that looks like follows:

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

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

I want to create a wrapper class ReadonlyWrapper that is read-only, with the following functionality:

# 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__ 之后,否则无法在构造函数本身中构造类.我知道可以使用属性装饰器来完成,但我不想将所有属性都转换为属性.

More precisely I want that all field of the class are read-only, but only after __init__ is called, otherwise the class cannot be constructed in the constructor itself. I know it can be done using the property decorator, but I do not want to turn all attributes into properties.

推荐答案

这可以通过以下方式覆盖 __setattr__ 来实现:

This can be achieved by overriding __setattr__ in the following way:

class ReadonlyWrapper(Base):
    _initialized = False

    def __init__(self, *args, **kwargs):
        super(ReadonlyWrapper, self).__init__(*args, **kwargs)
        self._initialized = True

    def __setattr__(self, key, value) -> None:
        if self._initialized:
            raise PermissionError()
        else:
            super().__setattr__(key, value)

一旦 _initialized 设置为 True,任何设置属性的尝试都会引发 PermissionError.

Once _initialized is set to True, any attempt to set an attribute will raise a PermissionError.

这篇关于Python创建只读包装类而不修改包装类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆