+ 1
How to achieve same result in python?
How do i create a static variable in python that will change everywhere if it is modified by any instance of the class? https://code.sololearn.com/c5y82awz4Zj1/?ref=app https://code.sololearn.com/c70Ly7DdQcxB/?ref=app
4 Antworten
+ 1
Easy way: use __class__ method to modify class attr as static variable
example:
t1.__class__.n = 6 <-- you change attribute of class, all instances of this class will print same value
t1.n = 6 <-- you create new attribute of instance t1, but it not change attribute of class
Little harder:
you can change logic of __setattr__ method so when changing for exampe "n" it changing in class when you use this:
t1.n = 6
+ 3
Test.n = 6
😊
+ 2
in Python, to change the value of the class attribute, you have to change it at the class level. object instances can however create and alter instance value. so you do something like this:
class A:
x = 5
a1 = A()
a2 = A()
print(f'{A.x = }, {a1.x = }, {a2.x = }')
A.x =100
print(f'{A.x = }, {a1.x = }, {a2.x = }')
and if you do
a1.x = 50
then using A.x = 1 will alter a2.x but cannot alter a1.x because you defined and created an independent instance value for x in a1.
but if you
del a1.x
then
a1.x will again reference the class attribute x.
+ 1
Everything is very simple 😉
class Test:
n = 5
t1 = Test
t2 = Test()
t1.n = 6
print(t1.n, t2.n, Test.n)