在Python中初始化类时执行由参数指示的类函数
我希望在一个类中创建函数,当它运行时,改变类的自身值。我还希望能够在初始化类时运行这些函数,希望能将它们作为参数传递 作为一个具体的例子,假设我有class在Python中初始化类时执行由参数指示的类函数,python,class,initialization,self,Python,Class,Initialization,Self,我希望在一个类中创建函数,当它运行时,改变类的自身值。我还希望能够在初始化类时运行这些函数,希望能将它们作为参数传递 作为一个具体的例子,假设我有classfoo,带有自我值thing和函数bar。初始化foo后,我想将bar作为参数传递,然后它将运行函数bar,并相应地更改内容。因此: Foo类: def uuu init uuuu(self,function-to-call): self.thing=“” self.function_to_call() def bar(自): self.th
foo
,带有自我值thing
和函数bar
。初始化foo
后,我想将bar
作为参数传递,然后它将运行函数bar
,并相应地更改内容。因此:
Foo类:
def uuu init uuuu(self,function-to-call):
self.thing=“”
self.function_to_call()
def bar(自):
self.thing=“诸如此类”
myClassInstance=Foo(巴)
打印(myClassInstance.thing)
所以,在这种情况下,我希望后一行返回“废话废话”,这可能吗?如果是,怎么做?目前,我被告知AttributeError:'Foo'对象没有属性'function\u to\u call'
您可以传递对未绑定类方法的引用:
class Foo:
def __init__(self, function_to_call):
self.thing = ""
function_to_call(self)
def bar(self):
self.thing = "blah blah blah"
myClassInstance = Foo(Foo.bar)
print(myClassInstance.thing)
结果:
blah blah blah
blah blah blah
旁白:我不清楚为什么要这样做,因为创建Foo后调用bar
行要简单得多。那么你根本不需要做任何函数传递
class Foo:
def __init__(self):
self.thing = ""
def bar(self):
self.thing = "blah blah blah"
myClassInstance = Foo()
myClassInstance.bar()
print(myClassInstance.thing)
另一种方法是将方法名作为字符串传递。然后可以使用getattr
获取绑定方法
class Foo:
def __init__(self, funcname):
self.thing = ""
getattr(self, funcname)()
def bar(self):
self.thing = "blah blah blah"
foo = Foo('bar')
print(foo.thing)
输出