Home > Net >  Instantiating and Using a Method of a Class Within a Function
Instantiating and Using a Method of a Class Within a Function

Time:01-21

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
def myclass(self):
    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?

CodePudding user response:

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)

CodePudding user response:

Define your class using the class keyword rather than def.

Create an instance of the class.

Define a function that will try to execute the function given by its name.

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

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


myclass_instance = myclass('Hello world')

def execute_function(instance, function):
    getattr(instance, function)()

execute_function(myclass_instance, 'myclass_func')

Output:

Hello world
  • Related