pythonfunctionclassobjectmethod-call

How to call a function from an object within a class?


Code Snippet.

class foo:
    def __init__(self, items):
        self.myObj = {
        "item one": self.functionOne(),
        "item two": self.functionTwo()
        }
        self.__handler()

    def __handler(self):
        for item in items:
            if item in self.myObj.keys():
                self.myObj[item]

    def functionOne(self):
        # do stuff

    def functionTwo(self):
        # do stuff

The problem. I am trying to call the correct function without the use of if statements. The result of running this code is: functionX takes 0 positional arguments but 1 was given.

Desired end state. Call the correct function using the object while inside of the class. Or guidance if there is a better way to do accomplish this.

Bigger picture. I expect the passed items count to change periodically. I would like to ensure my handler can manage the increase or decrease without modifying existing code (to an extent of the myObj).

Alternate plan. Incase what I am trying to accomplish is not possible, I am considering importing class foo into the higher level class that calls foo. Then passing an object with the functions already mapped. If someone could shed light on this alternative incase my desired end state is not possible.

Edits.

  1. Forgot to add the handler call inside the constructor.
  2. Corrected indentation and function definitions.
  3. Added commented solution (thanks kpie).

Solution by kpie.

class foo:
    def __init__(self, items):
        self.myObj = {
        "item one": self.functionOne, # removed () from original
        "item two": self.functionTwo # removed () from original
    }
    self.__handler(items)

    def __handler(self,items):
        for item in items:
            if item in self.myObj.keys():
                self.myObj[item]() # added () from original

    def functionOne(self):
        print("bar")

    def functionTwo(self):
        print("baz")

foo(["item one"]) # example test (1) item, output: bar
foo(["item two","item one"]) # example test (2) items, output: baz, bar

Solution

  • There is nothing stopping you from storing functions in a dictionary for lookup. Here is an example that shows the correct syntax.

    class foo:
        def __init__(self, items):
            self.myObj = {
            "item one": self.functionOne,
            "item two": self.functionTwo
            }
            self.__handler(items)
        def __handler(self,items):
            for item in items:
                if item in self.myObj.keys():
                    self.myObj[item]()
        def functionOne(self):
            print("bar")
        def functionTwo(self):
            print("baz")
    
    foo(["item one"])
    foo(["item two","item one"])
    

    prints:

    bar
    baz
    bar