0

我有 2 个文件。

  1. funcattrib.py
  2. test_import.py

funcattrib.py

import sys

def sum(a,b=5):
    "Adds two numbers"
    a = int(a)
    b = int(b)
    return a+b

sum.version = "1.0"
sum.author = "Prasad"
k = sum(1,2)
print(k)

print("Function attributes: - ")
print("Documentation string:",sum.__doc__)
print("Function name:",sum.__name__)
print("Default values:",sum.__defaults__)
print("Code object for the function is:",sum.__code__)
print("Dictionary of the function is:",sum.__dict__)

#writing the same information to a file

f = open('test.txt','w')
f.write(sum.__doc__)
f.close()
print("\n\nthe file is successfully written with the documentation string")

test_import.py

import sys
from funcattrib import sum

input("press <enter> to continue")

a = input("Enter a:")
b = input("Enter b:")
f = open('test.txt','a')
matter_tuple = "Entered numbers are",a,b
print(matter_tuple)
print("Type of matter:",type(matter_tuple))
matter_list = list(matter_tuple)
print(list(matter_list))
finalmatter = " ".join(matter_list)
print(finalmatter)
f.write(finalmatter)
f.close()
print("\n\nwriting done successfully from test_import.py")

sumfuncattrib.py. 当我尝试执行 test_import.py 时,我看到了整个funcattrib.py. 我只是想使用该sum功能。

请指教,我做错了什么,或者有没有其他方法可以在不实际执行的情况下导入模块?

4

2 回答 2

4

导入时执行模块“顶级”中的所有语句。

希望这种情况发生,您需要区分用作脚本的模块和模块。为此使用以下测试:

if __name__ == '__main__':
    # put code here to be run when this file is executed as a script

将其应用于您的模块:

import sys

def sum(a,b=5):
    "Adds two numbers"
    a = int(a)
    b = int(b)
    return a+b

sum.version = "1.0"
sum.author = "Prasad"

if __name__ == '__main__':
    k = sum(1,2)
    print(k)

    print("Function attributes: - ")
    print("Documentation string:",sum.__doc__)
    print("Function name:",sum.__name__)
    print("Default values:",sum.__defaults__)
    print("Code object for the function is:",sum.__code__)
    print("Dictionary of the function is:",sum.__dict__)

    #writing the same information to a file

    f = open('test.txt','w')
    f.write(sum.__doc__)
    f.close()
    print("\n\nthe file is successfully written with the documentation string")
于 2013-03-19T19:43:35.637 回答
2

Python 总是从上到下执行。函数定义是可执行代码,就像其他任何东西一样。导入模块时,该模块顶层的所有代码都会运行。Python 必须全部运行,因为函数是代码的一部分。

解决方案是保护您不希望在if __name__=="__main__"块下导入时运行的代码:

if __name__ == "__main__":
     print("Some info")
于 2013-03-19T19:43:46.740 回答