Global class in python

Question:

I am looking to create a run configuration class called Global that will store important variables. This class will be passed to many classes and their children. For example:

class Global:
    def __init__(self):
        self._var = 1

    @property
    def var(self):
        return self._var

class parent:
    def __init__(self, GLOBAL):
        self.GLOBAL = GLOBAL
        print(self.GLOBAL.var) # this works

class child(parent):
    def __init__(self):
        print(self.GLOBAL.var) # this doesn't work (because referencing the parent's instance variable)

How can I make the Global class accessible to all children of the parent class (without passing it to each child’s constructor)? I also tried creating a class variable in the parent class and assigned it’s value when the class is initialized. However, that didn’t work.

Also, if there is a better way to store mutable run configurations and pass them to many classes and their children I’d be happy to change my strategy.

Thanks a ton in advance!

Asked By: Michael Berk

||

Answers:

  1. Your child class should call parent __init__ method like this:

    super().__init__(…)

Otherwise you won’t set GLOBAL field at all. I guess you can read more here.

  1. You want to create a global object, don’t you? I mean, not a class, but the object of that class, because you’re accessing variable var in your constructor. Anyway, you can just create a variable in your module scope and use it.

    Global:

    OtherClass:
    def run(self):
    print(_global_settings)

    _global_settings = Global() # or something similar

  2. You’d better follow PEP8 style if possible, then your code will be easier to read and understand. In particular, capitalize your class names and use lowercases for class fields.

Answered By: stardust

If your child class does not override the constructor __init__, then parent.__init__ will be used when constructing child objects, and you will get the functionality you want. If you need to write specialized constructors to your derived classes, however, you will need to pass the Global object to an explicit call of the parent.__init__ constructor within child.__init__.

Python does not have automatic constructor chaining.

Answered By: Amitai Irron
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.