Alexis
Alexis

Reputation: 521

Static variables being shared between parent and child classes

I encountered a bug in my code that turned me crazy for a bit. Essentially I have a parent class that instantiates a static variable, and a Child class that instantiates the same static variable, differently. This should be fine, because Parent.variable should be != to Child.variable. Well depends in what order you instantiate them.

i = 0

class Parent():
    
    _value = None
    
    @classmethod
    def get_value(cls):
        if cls._value is None:
            global i
            i += 1
            cls._value = i
        
        return cls._value


class Child(Parent):
    pass

Run:

print("Child: ", Child.get_value())
print("Parent: ", Parent.get_value())

Output:

Child: 1

Parent: 2

Run:

print("Parent: ", Parent.get_value())
print("Child: ", Child.get_value())

Output:

Parent: 1

Child: 1

See below:

enter image description here

Is this wanted behavior?

Upvotes: 0

Views: 738

Answers (1)

LhasaDad
LhasaDad

Reputation: 2143

In the first case the cls._value is set on the child then the 2nd call does not see it for parent and it runs the increment code again.

In 2nd case it sets it up in the base and then when called for child it can see it in the hierarchy and returns the value.

Watch the flow with the debugger and check the attributes show, etc. will help explain that.

Upvotes: 1

Related Questions