我正在测试一个小功能,barbar
中的manage()
函数调用call_central
,其中包含函数call2和call3。
我想在call_central
上创建一个对象,以便在需要时调用call2
和call3
。你知道吗
一些背景:我打算做的是。在我的程序中,call2正在实例化另一个类,而call3正在使用此信息执行其他各种操作。你知道吗
编辑:更多详细信息: 我创建嵌套函数的基础如下。假设您正在尝试执行一些调度工作并测试各种调度程序。barbar函数将从您要实现的“所有”调度算法中获取所有参数。每个调度算法本身都有类。在这个MWE中,它被称为ThisClass。“call\u central”所做的是在call2中实例化这个特定的调度算法,并使用它在call3中实际调度
有几个问题:
s(self).call2()
返回None
代码:
#!/usr/bin/env python3
class CallThisClass:
def __init__(self):
pass
def do_something_here(self):
while True:
print ("doing something")
class CallThisClass1:
def __init__(self):
pass
def do_something_here(self):
while True:
print ("doing something")
class barbar:
def __init__(self, which_function=None):
print ("do nothing")
self.which_function = which_function
self.manage()
def manage(self):
FUNCTIONS = globals()['barbar']
s = getattr(FUNCTIONS, self.which_function)
print (s(self))#.call2())
def call_central(self):
print ("in call central")
def call2():
self.invoke_callthisclass = CallThisClass()
print ("do nothing from call2")
def call3():
self.invoke_callthisclass.do_something_here()
print ("do nothing from call3")
return 0
def call_central2(self):
print ("in call central")
def call4():
self.invoke_callthisclass1 = CallThisClass1()
print ("do nothing from call4")
def call5():
self.invoke_callthisclass1.do_something_here()
print ("do nothing from call5")
return 0
d = barbar(which_function="call_central")
你在做一些很奇怪的事情,但我会尽量给出一些合理的答案。你知道吗
为什么它要我把“自我”当作一个论据。
您的代码如下所示:
与其通过
globals
dict,不如等价地编写s = barbar.call_central
。barbar.call_central
是一个未绑定的方法。这意味着它是一个实例级方法,没有任何实例可供调用。你知道吗作为Python中对象如何工作的快速迂回,让我们讨论一个更简单的类:
所以,
f
是类Foo
的一个实例。bar
是一个实例方法-Foo的实例可以调用这个方法。Foo.bar
没有绑定到任何实例;要调用它,它需要一个Foo
的实例。f.bar
是方法Foo.bar
,绑定到实例f
。所有这些绑定意味着,无论何时调用该方法,绑定实例都会作为第一个参数传入。这意味着f.bar()
和Foo.bar(f)
做基本相同的事情。你知道吗那么,为什么需要将
self
作为参数传递给barbar.call_central
?因为barbar.call_central
是一个未绑定的实例方法,需要调用一个实例。self.call_central
是绑定方法,您可能需要调用它。getattr(self, self.which_function)
将为您提供绑定方法。你知道吗为什么s(self).call2()返回None
这是call2的定义:
没有
return
,执行只会从末尾掉下来。当执行从函数的末尾停止时,它返回None
。你知道吗你写过这样的东西:
因为您取消了indent,所以离开了
call2
的范围,所以下面的行都与该函数无关。值得指出的是,call3
也永远不会return 0
,因为您的do_something_here
方法永远不会返回。你知道吗有没有办法避免为此使用嵌套函数?
据我所知,你的问题似乎就是你想做的:
您说过您希望
__init__
方法对所有可用的调度程序执行某些操作,所以__sublcasses__
位就是这样做的。参见:How to find all the subclasses of a class given its name?。其他的一切都很简单。你知道吗
相关问题 更多 >
编程相关推荐