Python模块更改问题

2024-04-26 06:07:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手。下面是我的模块

你知道吗我的数学.py你知道吗

pi = 3.142

def circle(radius):
    return pi * radius * radius

在终端中,我按以下方式运行:

>>import mymath
>>mymath.pi
>>3.142

当我将pi改为局部变量并重新加载(mymath)并导入mymath时,仍然得到我的数学.pi同于3.142。然而我的数学圈(半径)确实反映了结果的变化。你知道吗

def circle(radius):
    pi = 3
    return pi * radius * radius

>>import imp
>>imp.reload(mymath)
>>import mymath
>>mymath.pi
>>3.142
>>circle(3)
>>27

有人能告诉我问题出在哪里吗?你知道吗


Tags: 模块pyimport终端returndef方式pi
1条回答
网友
1楼 · 发布于 2024-04-26 06:07:39

^{}的文档中:

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains.

因此,当您执行imp.reload(mymath)操作时,即使pi不再作为全局名称存在于模块代码中,旧定义仍然作为更新模块的一部分。你知道吗

如果您真的想从头开始,请使用以下方法:

import sys
del sys.modules['mymath']
import mymath

例如:

>>> import os
>>> os.system("echo 'pi = 3.142' > mymath.py")
0
>>> import mymath
>>> mymath.pi
3.142
>>> os.system("echo 'pass' > mymath.py")
0
>>> import sys
>>> del sys.modules['mymath']
>>> import mymath
>>> mymath.pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pi'

相关问题 更多 >