cv2 onMouse() has a missing argument when using importlib to create a class at runtime

Question:

I want to load a python file (module) dynamically when the user inputs the filename (here for example: RegionOfInterest.py). In the file will be one class (here: RegionOfInterest). All classes have a method with the same name (here: start) which i want to call.

This works fine, but if i call another method from the start method i get an error:
TypeError: testMethod() missing 1 required positional argument: ‘self’

Any help is greatly appreciated. 🙂

Minimal Working Example:

main.py

import importlib

if __name__ == '__main__':
    module_name = "RegionOfInterest"    # will be user input
    class_name = module_name            # same as module_name

    myModule = importlib.import_module(f"{module_name}")
    myClass = myModule.__getattribute__(class_name)
    myClass.__init__(myClass)           # apparently is not called automatically ?
    myMethod = myClass.__getattribute__(myClass, "start")
    myMethod(myClass)


RegionOfInterest.py

class RegionOfInterest:

    def start(self):
        self.testMethod()

    def testMethod(self):
        pass
Asked By: ImNotARobot

||

Answers:

I’m not sure what you’re trying to achieve with this code:

myClass.__init__(myClass, img)
myMethod = myClass.__getattribute__(myClass, "start")
myMethod(myClass)

myClass is a class, not an instance of that class. So your passing an invalid object as self to the __init__() method.

The following seems much simpler to me and does work without the error:

module_name = "RegionOfInterest"  # will be user input
myModule = importlib.import_module(f"{module_name}")
myClass = myModule.__getattribute__(module_name)
roi = myClass(img)
roi.start()

(Note: this answer was based on earlier revision of the question. The code has been changed a bit since then, but the principle remains the same.)

Answered By: wovano
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.