导入和独立函数

Imported And Standalone Functions

我的代码有逻辑错误和错别字,已编辑并发布在这里

第一个文件:foo.py

import bar
def myname_foo():
    if __name__=='foo':
        print("foo: I have been imported")
    if __name__=='__main__':
        print("foo: I am on my own, i.e., standalone")

if __name__=='__main__':
    myname_foo()
    bar.myname_bar()

第二个文件:bar.py

import foo
def myname_bar():
    if __name__=='bar':
        print('bar: I have been imported')
    if __name__=='__main__':
        print('bar: I am on my own, i.e., standalone')

if __name__=='__main__':
    myname_bar()
    foo.myname_foo()

输出是:

$ python foo.py
foo: I am on my own, i.e., standalone
bar: I have been imported
$ python bar.py
bar: I am on my own, i.e., standalone
foo: I have been imported

你打错了,应该用__main__代替main。以 main — Top-level script environment 为例。

你应该更好地检查你的代码

import foo
def myname_bar():
    if __name__=='foo':
                  ^^^ bar  


if __name__=='__main__':
    myname_bar()
    bar.myname_foo()
    ^^^ foo

之后

$ python  foo.py
foo: I am on my own, i.e., standalone
bar: I have been imported

$ python  bar.py
bar: I am on my own, i.e., standalone
foo: I have been imported