【发布时间】:2021-03-18 15:22:20
【问题描述】:
我有一个如下所示的基类:
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__ 之后,否则无法在构造函数本身中构造该类。
我知道可以使用属性装饰器来完成,但我不想将所有属性都变成属性。
【问题讨论】:
标签: python python-3.x inheritance wrapper setattr