0
How to make a valuable immutable in python?
if I create a variable x and assign it a value say 7 i.e. x=7. I can again assign a value x=8. And this will continue. So I wish to restrict it to first assignment. How do I do this?
2 Antworten
+ 6
There are no constants in python.
You can create a class and declare an instance variable as a read-only property:
class Const():
def __init__(self, val):
self._val = val
@property
def val(self):
return self._val
c = Const(5)
print(c.val) # 5
c.val = 85 # error: can't set attribute
But even that won't prevent you from just reassigning a whole different type/value to your "constant":
c = 'hi' # no problem
+ 1
You could use a tuple instead... It would look something like this:
x = (7,)
tuples are immutable, but unfortunately they can still be overwritten...so this would not help in your case :/