I'm trying to make value inside a class non-changeable, while making it accessible with the class name.
Here's my code snippet:
class readonly:
def __init__(self, val):
self.val = val
def __get__(self, instance, owner):
return self.val(owner)
def __set__(self, instance, value):
raise AttributeError("Value can't be changed")
class A:
@readonly
def abc(value):
return 5
Result and Problem
In [1]: A().abc
Out[1]: 5
In [2]: A.abc
Out[2]: 5
In [3]: A().abc = 2
Traceback (most recent call last):
File "<ipython-input-105-ba63e690d374>", line 1, in <module>
A().abc = 2
File "<ipython-input-101-24787a3d51ab>", line 9, in __set__
raise AttributeError("Value can't be changed")
AttributeError: Value can't be changed
In [4]: A.abc = 2
In [5]: A().abc
Out[5]: 2
Here, A().abc
is restricting changes made to abc
, but A.abc
fails.
What I expect
Both A().abc
and A.abc
should restrict any changes made to abc
Awaiting valuable reply
Thanks!
Preetkaran
Python Ver: 3.7.7