Python循环调用


在设计较为复杂的python程序时,容易导致循环调用的问题。

显式循环调用

在python中只要两个模块相互引用了对象,那么就会构成循环调用,python解释器直接报错。即便两个模块引用的对象本身是不构成困惑的。下面举个例子

file: ps.py
from tp import print_tp


def print_ps():
    print("ps")


def test_tp():
    print_tp()

file: tp.py
from ps import print_ps


def print_tp():
    print("tp")


def test_ps():
    print_ps()

那么上述文件中不论是调用test_ps()还是test_tp()都会导致循环调用。
ImportError: cannot import name ‘print_tp’ from partially initialized module ‘tp’ (most likely due to a circular import)

隐式循环调用

模块A直接引用B的内容,而B则通过函数传参调用A的内容。这种情形下python是不会报错的。继续上边的例子:
保持file: ps.py不变,tp.py修改为如下,然后将print_ps通过参数func传入test_ps,那么python将不会报错。

file: tp.py
def print_tp():
    print("tp")


def test_ps(func):
    func()

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值