简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM