导入和独立功能

时间:2020-07-12 10:47:54

标签: python cygwin

我的代码中存在逻辑错误和错字,已在此处进行编辑和发布

第一个文件: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

2 个答案:

答案 0 :(得分:1)

您有错字,应使用__main__而不是main。参见main — Top-level script environment作为示例。

答案 1 :(得分:1)

您应该更好地检查代码

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