首页 > 解决方案 > Python:如何在函数内部显式传递函数

问题描述

所以我知道可以将函数传递给函数。但我正在使用某个库,它有一个成员变量和一个同名的函数。如何告诉python在函数内部传递函数而不是成员变量?

以下示例代码显示 python 会错误地认为我正在传递成员变量:

class foo():
    def __init__(self):
        self.ambiguous = "member variable" # Member variable I don't want to be passed into another function

    def ambiguous(self): # Function I want to be passed into another function
        print("function")

def testFunc(func): # This function is intended to be passed a function
    func()

def main():
    myFoo = foo()
    testFunc(myFoo.ambiguous) # this will pass the member variable (I want to pass the function)

if __name__ == "__main__":
    main()

我正在使用 python 3.5

标签: python-3.5

解决方案


推荐阅读