首页 > 解决方案 > 如何从 foo.py 访问 show()?

问题描述

foo.py

def show():
    print("x is from foo")

酒吧.py

def show():
    print("x is from bar")

foob​​ar.py

from foo import *
from bar import *
show()

我想show()foo.py.

我的尝试:

foob​​ar.py

from foo import *
from bar import *
#Don't change the above two lines. Keep them as it is. 
import gc 

show() #Calls show() from bar.py

found = [] 
for obj in gc.get_objects():
    if type(obj) == type(show):
        found.append(obj)

print(found)

如何show()访问foo.py

标签: pythonimportmodule

解决方案


好吧,由于您导入文件的方式以及它们都具有相同的函数名 ("show"),因此只能访问"bar.py"中的函数,从而覆盖"foo.py" 的函数,因为“ foo.py”首先被导入

因此,您需要更改导入方法。代码应如下所示:

import foo
import bar
import gc 

bar.show() #Calls show() from bar.py
foo.show() #Calls show() from foo.py

found = [] 
for obj in gc.get_objects():
    if type(obj) == type(show):
        found.append(obj)

print(found)

小心


推荐阅读