How do I specify inheritence behavior on initialization of an object in Python?

Question:

I’m trying to write a class with a method that behaves differently based on data given on the initialization of the object. I want to pass this object code to run stored in a different file. The behavior should be as follows

foo = Myclass(config="return_a.py")
bar = Myclass(config="return_b.py")

foo.baz() # returns a
bar.baz() # returns b

# where return_a.py and return_b.py are files in the directory

The closest I’ve come to fixing it so far is using exec and having my configured python write to a file which I then read from. I don’t know how I’d do this in memory

Asked By: Secureighty

||

Answers:

You can use importlib to import the files dynamically.

Let’s say your project has the structure:

.
├── main.py
├── return_a.py
└── return_b.py

you can put in main.py your code:

import importlib

class Myclass:

    def __init__(self, config) -> None:
        config = importlib.import_module(
            config)
        self.baz = config.baz

foo = Myclass(config="return_a")
bar = Myclass(config="return_b")

foo.baz()
bar.baz()

This is assuming you have the function baz your return_a and return_b files. For example:

#return_a.py
def baz():
    print("I am A")

#return_b.py
def baz():
    print("I am B")

Now if you execute main.py you will get:

I am A
I am B
Answered By: zaki98
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.