+ 3
Is there any way to make class attributes unchangeable, so one cannot change not for class, nor for the object of the class?
5 odpowiedzi
+ 9
Just mark it with underscore or double underscore in a variable to mark it as protected or private. I think it was mentioned there in the OOP lesson (in the yellow box) that variables in class are not unchangeable based on Python philosophy about encapsulation.
_legs = 4
or
__legs = 4
To access: object._className__attribute
Though you can make the Class variable constant (not really) and unchangeable by using the __setattr__ dunder to change back the value of legs to 4 everytime the program is setting a new value to the attribute.
See this for example:
https://code.sololearn.com/ca3A56A19A0a
+ 5
To add to what 《 Nicko12 》 has posted, Python doesn't have a true constant nor does it have true protected or private members like other languages (C, C++, Java, etc). Constants are more of a convention than anything. Using a prefixed underscore or double underscore will restrict access, but not prevent it completely.
Here is some additional information:
https://www.tutorialsteacher.com/python/public-private-protected-modifiers
https://www.programiz.com/python-programming/variables-constants-literals
https://medium.com/better-programming/does-python-have-constants-3b8249dc8b7b
+ 2
《 Nicko12 》 regarding the using __setattr__ dunder: is it possible to detect, that the user tried to change the 'protected' attribute? If so, how to warn him? e.g. print out text: "You tried to change legs attribute by assigning it X(the value, that user tried to assign)." Is it possible?
+ 2
I just found out that when using the Class name itself, the __setattr__ method is not called, I'll try to figure out to overload even when using the class name itself and not just the object.
For now, here's what you've asked for.
https://code.sololearn.com/ca7a217A24A1
0
Yeah