Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The child class does not call code of the parent class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading