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

Time:01-01

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

CodePudding user response:

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
  • Related