Search code examples
pythonfunctionclassparametersinstantiation

Instantiating and Using a Method of a Class Within a Function


I'm trying to instantiate a class within a function, then call a method within the class inside the same function, like this:

# Define the class
class myclass:
    def __init__(self,string_to_print):
         self.string_to_print = string_to_print

    def myclass_func(self):
         print(self.string_to_print)


# Define the function that utilizes the class
def func(class,func,str)
    instance = class(str)
    class = class.func()


# Run the function that utilizes the class
func(myclass,myclass_func,str)

But I am getting an error like "'myclass' object is not callable". Why is this? Additionally, I expect my 'class = class.func()' line is wrong; if it is, what is the correct way to call the method from the recently instantiated class?

Edit: fixed mistake in class declaration


Solution

  • You can't use method names as global variables. If you want to call a method dynamically, pass its name as a string and use the getattr() function.

    # Define the class
    class myclass:
        def __init__(self,string_to_print):
             self.string_to_print = string_to_print
    
        def myclass_func(self):
             print(self.string_to_print)
    
    
    # Define the function that utilizes the class
    def func(class,func,str)
        instance = class(str)
        return getattr(instance, func)()
    
    
    # Run the function that utilizes the class
    func(myclass,'myclass_func',str)