0

In Python, I want to define a top level class that can depend on a class variable. Then I want to be able to change that variable at the class level, for children of the class, but still inherit the functionality that uses that variable.

In general, my Parent class has some functions that depend on configuration variables. All my child classes use those same functions, but with different parameters. I would like to be able to change the parameters at the class level.

As the simplest example, here are two classes where the Parent defines functions in terms of my_global, then the Child attempts to change that variable (but fails)

class Parent():
    my_global = "parent"
    
    def _init_(self):
        pass

    def printmg(self):
        print(Parent.my_global)


class Child(Parent):
    my_global = "child"


my_parent = Parent()
my_parent.printmg()
my_child = Child()
my_child.printmg()

This outputs

parent
parent

While I would like it to output

parent
child

I don't wan't to keep the variables at the object level (i.e. self.my_global = "child"), or to rewrite the function for the child.

1
  • 3
    Change print(Parent.my_global) to print(self.my_global). Commented Feb 9, 2023 at 19:14

2 Answers 2

1

Change the line print(Parent.my_global) to print(self.my_global).

The self operater represents the current class. So printing like this will work.

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't need an instance method define printmg as classmethod:

@classmethod
def printmg(cls):
    print(cls.my_global)

1 Comment

Oh, great! Not what I was looking for but good to know that I can do that too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.