Home > other >  The child class does not call code of the parent class
The child class does not call code of the parent class

Time:02-19

The child class does not call code of the parent class. I wrote this code. I thought the Id field of the Extension2 class would be 2, but it is 1

myvariable = 0
lock = threading.Lock()


def get_next_id() -> int:
    global myvariable
    global lock
    with lock:
        myvariable  = 1
        return myvariable


class Extension:
    Id = get_next_id()


class Extension2(Extension):
    pass

enter image description here

CodePudding user response:

Defining Id in the parent class only defines it once. Children inherit this value, but the expression isn't re-evaluated. You can use __init_subclass__ to force evaluation on every subclass, sort of like __init__ does for instances.

class Extension:
    Id = get_next_id()

    @classmethod
    def __init_subclass__(cls):
        cls.Id = get_next_id()

Try it online!

CodePudding user response:

The way you have structured your class, Id is not an instance variable for the class. You probably want to use __init__ to initialize data members of a class. For example:

def set_variable():
    return "id"

class Extension():
    def __init__(self):
        self.Id = set_variable()

class Extension2(Extension):
    pass

Then when you create class instances, their members are automatically assigned, and this is true of the child class as well, which will inherit instance variables of the parent unless you specify otherwise.

r = Extension()
s = Extension2()

r.Id and s.Id will both be set to "id"

  • Related