我试图在一个函数中实例化一个类,然后在同一个函数中调用类中的一个方法,像这样:
# 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)
但我得到一个错误,如&;'myclass'对象是不可调用的&;为什么会这样?此外,我希望我的'class = class.func()'行是错误的;如果是,从最近实例化的类调用方法的正确方法是什么?
编辑:修正类声明中的错误
不能使用方法名作为全局变量。如果你想动态调用一个方法,把它的名字作为字符串传递,并使用getattr()
函数。
# 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)
使用class关键字而不是def定义你的类。
创建类的实例。
定义一个函数,该函数将尝试执行其名称给出的函数。
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')
输出:
Hello world