获取作为参数传递给父函数的函数的名称

2024-05-18 14:49:58 发布

您现在位置:Python中文网/ 问答频道 /正文

给定下面的代码,如何打印作为self.looper(_function=)参数传入的子进程的名称?我不知道怎么做!我正在尝试根据传递到_function的函数来执行逻辑。希望我正确地表达了这个问题。谢谢

class okheregoes(object):

    def __init__(self):
        pass


    def looper(self, _function):
        print('the function name that was passed to _function is {}'.format(_function.__name__))
        if _function.__name__ == 'child1':
            print('it was child 1 this time')
        if _function.__name__ == 'child2':
            print('it was child 2 this time')



    def child1(self, _number):
        return 'my favorite number is {}'.format(_number)

    def child2(self, _number):
        return 'my favorite number is {}'.format(_number)

    def main(self):
        for i in range(1,10):
            self.looper(_function=self.child1(_number=i+1))
            self.looper(_function=self.child2(_number=i-1))





pleashelp = okheregoes()

if __name__ == '__main__':
    pleashelp.main()

Tags: nameselfformatnumberifismaindef
2条回答

您没有将函数或子进程传递给dictlooper(你甚至没有使用子进程。)你在传递字符串。这些字符串是由名为child1child2的函数返回的,但是Python没有记录字符串所包含的函数

没有什么可以代替wtfisthis来获取函数名信息。您必须更改代码的其余部分,可能是通过实际传递函数

您需要用_function.__name__替换wtfisthis

请注意,您是在向self.dictlooper传递字符串而不是函数。要解决此问题,请如下定义child1和child2:

def child1(self, _number):
    def inner():
        return 'my favorite number is {}'.format(_number)
    return inner

相关问题 更多 >

    热门问题