gpt4 book ai didi

Python:导入模块

转载 作者:太空狗 更新时间:2023-10-29 22:16:35 25 4
gpt4 key购买 nike

假设我有一个 python 模型 fibo.py 定义如下:

#Fibonacci numbers module
print "This is a statement"
def fib(n):
a,b = 0,1
while b < n:
print b
a, b = b, a+b

def fib2(n):
a,b = 0,1
result= []
while(b < n):
result.append(b)
a, b = b, a+b
return result

在我的口译 session 中,我执行以下操作:

>> import fibo
This is a statement
>>> fibo.fib(10)
1
1
2
3
5
8

>>> fibo.fib2(10)
[1, 1, 2, 3, 5, 8]
>>> fibo.__name__
'fibo'
>>>

到目前为止一切顺利...重启解释器:

>>> from fibo import fib,fib2
This is a statement
>>> fibo.__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fibo' is not defined
>>>

我预料到了这个错误,因为我只导入了 fibfib2。但是我不明白为什么我只导入了fibfib2就打印了语句。

其次,如果我将模块更改为:

#Fibonacci numbers module
print "This is a statement"
print __name__

预期的结果应该是什么?

最佳答案

这是预期的行为。当您使用 from X import Y 导入时,模块仍会加载和执行,如 Language Reference 中所述。 .事实上,当你这样做的时候

from fibo import fib
print("foo")
import fibo

将打印This is a statement,然后是foo。第二个 import 不打印任何内容,因为模块已经缓存。

您的第二个模块将打印 This is a statement 后跟 fibo。该模块在加载时知道自己的名称。

关于Python:导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10993156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com