I want to create object which is having read-only attributes. And it need to be initialize dynamically.
Here is situation I want.
readOnlyObject = ReadOnlyClass({'name': 'Tom', 'age': 24}) print(readOnlyObject.name) >> 'Tom' print(readOnlyObject.age) >> 24 readOnlyObject.age = 14 >> AttributeError: can't set attribute I found a way using property function,
but I think property function only works on attributes that is pre-declared.
Here is my code that property doesn't work.
class ReadOnlyClass: _preDeclaredVar = "Read-Only!" preDeclaredVar = property(lambda self: self._preDeclaredVar) def __init__(self, data: dict): for attr in data: setattr(self, '_' + attr, data[attr]) setattr(self, attr, property(lambda self: getattr(self, '_' + attr))) readOnlyObject = ReadOnlyClass({'name': 'Tom', 'age': 24}) print(readOnlyObject.preDeclaredVar) >> "Read-Only!" readOnlyObject.preDeclaredVar = "Can write?" >> AttributeError: can't set attribute ' print(readOnlyObject.name) >> <property object at 0x016C62A0> # I think it is weird.. property func only work on pre-declared variable? what happened?
I want to know is there a way to create read-only object dynamically.
__get__is called on the type.