声明一个不存在的函数

Declaring a non-existing function

我试图了解 python 的工作原理,我需要一个简短的解释。
所以我写了一个非常简短的例子,但我很难理解为什么它不起作用。 我创建了一个 test.py:

def a():
    print('a() try to call non existing b()')
    b()

在这个阶段,如果我写成python shell

>>> import test
>>> test.a()

没用是正常的,因为b()未知。
但是当我写下这些行时,它仍然不起作用。

>>> import test
>>> def b():
...     print('b()')
... 
>>> test.a()

python模块中的函数只能调用当前模块和导入模块中的函数?

您必须在定义 a() 的同一 test.py 中定义 b()

如果您创建了一个新的 python 模块(python 文件),其中定义了 b(),然后将该模块导入到 test.py

from another_module import b # refers to function b

def a():
    print("this function calls b")
    b()

像上面那样的东西会起作用。请记住,包含函数 b() 的模块和 test.py 模块应该位于同一目录中才能正常工作。

您可以通过将函数 b 作为参数传递给 a 来实现我认为您正在描述的行为。

def a(b):
    print('called a')
    # Use the callable argument
    b()
def x():
    print('x')
a(x)

输出:

called a
x

你可以重新定义 b

How do I redefine functions in Python

import test

def b():      # definition of b
  print('b()')

test.b = b  # function b redefined for test

test.a()   # now this works