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

Shared Variable between Parent and Child in Python

I have a global configuration pp that changes at runtime and needs it to be shared across all parent/child objects.

class Config:
    pp = 'Init'
    def __init__(self):
        pass
    
class Child(Config):
    def __init__(self, name):
        self.cc = name

par = Config()
print(f"Parent: {par.pp}")
par.pp = "123"
print(f"Parent: {par.pp}")
child = Child('XYZ')
print(f"Child-1: {child.pp} - {child.cc}")

This prints:

Parent: Init 
Parent: 123 
Child-1: Init - XYZ

The third line is expected to be Child-1: 123 - XYZ

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

How can I implement that in a clean way?

UPDATE*
Currently it works with a method like:

class Config:
    pp = 'Init'
    def __init__(self):
        pass
    def set_pp(self, val):
        type(self).pp = val

>Solution :

In your example, the parent of Child is not par (which is an instance of Config, but it is the class Config. So you could change the value directly on the class, like that:

class Config:
    pp = 'Init'
    def __init__(self):
        pass
    
class Child(Config):
    def __init__(self, name):
        self.cc = name

print(f"Parent: {Config.pp}")
Config.pp = "123"
print(f"Parent: {Config.pp}")
child = Child('XYZ')
print(f"Child-1: {child.pp} - {child.cc}")

Note that if you want to keep the same syntax, you could write

class Config:
    _pp = "Init"

    @property
    def pp(self):
        return self._pp
    
    @pp.setter
    def pp(self, value):
        self.__class__._pp = value

    def __init__(self):
        pass
    
class Child(Config):
    def __init__(self, name):
        self.cc = name

par = Config()
print(f"Parent: {par.pp}")
par.pp = "123"
print(f"Parent: {par.pp}")
child = Child('XYZ')
print(f"Child-1: {child.pp} - {child.cc}")

In this version, the pp is set from the parent object, to the class Config.

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