i'm python newbie, and member variable of class works weird in my python code. some works like normal variable, but some works like static variable!
class Chaos:
list_value = []
value = "default"
def set_value(self, word):
self.list_value.append(word)
self.value = word
def show(self, num):
print(str(num) + "====")
print("value : " + self.value)
for st in self.list_value:
sys.stdout.write(st)
print("\n=====\n")
a = Chaos()
a.show(0)
a.set_value("A")
a.show(1)
b = Chaos()
a.show(2)
b.show(3)
result
0====
value : default
=====
1====
value : A
A
=====
2====
value : A
A
=====
3====
value : default
A
=====
but the last result of the test is different from what i expected in last test. There should be no "A" in the 'list_value' of the instance of 'b'. It was just created, and never have been added 'A' before. I added 'A' to the instance of 'a', not 'b'. But the result show me that there are also 'A' in 'b' More over, the 'list_value' and the 'value' in the class works differently. It looks like the both have same syntax. why do they work differently?
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops. Instance variables can be accessed directly by calling the variable name inside the class.
Practical Data Science using Python When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.
Instance variables are just variables defined inside a class, and every instance of a class can have a different value for an instance variable. In this module, we'll look at defining static variables in our Java classes. Static variables are also defined as variables inside a class, but with the keyword 'static'.
In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).
Those are, in fact, class variables. To create instance variables, initialize them in the __init__
function:
class Chaos:
def __init__(self):
self.list_value = []
self.value = "default"
The reason value
is behaving like instance variables is because you're setting it using self.value
. When Python sees self.X
it looks if there's a property X
in your object, and if there is none, it looks at its class. Since you never set self.list_value
, it's accessing the class variable, that is shared among all instances, so any modifiations will reflect in every other object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With