python member variable of instance works like member variable, and some works like static variable

python member variable of instance works like member variable, and some works like static variable

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 youre setting it using self.value. When Python sees self.X it looks if theres a property X in your object, and if there is none, it looks at its class. Since you never set self.list_value, its accessing the class variable, that is shared among all instances, so any modifiations will reflect in every other object.

The key difference is that you are appending to list_value, and you are assigning to value. They are called class variables. Each instance has its own reference to the class variable, which is why the list is shared. However, when you assign, you are changing that instances reference to point to a different variable, which explains the behavior of value.

If you are looking for instance variable behavior from list_value, initialize it in the constructor (a class method called __init__) instead.

python member variable of instance works like member variable, and some works like static variable

Leave a Reply

Your email address will not be published.