Also, you can use python __setattr__ magic method to control whatever will be run when setting an attribute. That will be helpful when making immutable values.
classConstants:def__setattr__(self,name,value):ifnameinself.__dict__:raiseException(f"Cannot change value of {name}.")self.__dict__[name]=valuea=Constants()a.b=2print(a.b)a.b=1print(a.b)
The output will be
2Traceback(mostrecentcalllast):File"python.py",line13,in<module>a.b=1File"python.py",line4,in__setattr__raiseException(f"Cannot change value of {name}.")Exception:Cannotchangevalueofb.
But technically it will still be mutable because
a.__dict__["b"]=1
Python magic methods are really cool, whoever doesn't know about Python's magic methods should read rszalski.github.io/magicmethods/
Thanks for your beautiful post!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Also, you can use python
__setattr__
magic method to control whatever will be run when setting an attribute. That will be helpful when making immutable values.The output will be
But technically it will still be mutable because
Python magic methods are really cool, whoever doesn't know about Python's magic methods should read rszalski.github.io/magicmethods/
Thanks for your beautiful post!