Python模块和全局变量

2024-09-29 02:24:42 发布

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

有很多帖子都有类似的标题,但都没有回答我的问题

我有一个对函数进行分析的代码。函数的定义在一个模块中,例如definition.py。假设内容是

# module definition.py
def f(x):
   return x**2

用于执行分析的所有函数都放在不同的模块中,例如analysis.py

# module analysis.py
def factor2(x):
   return 2*f(x)

我希望主代码看起来像这样

# main.py
from definition import *
from analysis import *

print( factor2(3.0) )

并期望看到结果“18.0”

注意,我不想在factor2的定义中显式地指定函数f。这是行不通的。编译器说没有定义名称f

我可以将函数factor2定义为factor2(f,x),然后传递参数f。但这正是我试图避免的。这是因为整个代码的目的是只在f上工作,并且一遍又一遍地编写该f是很乏味的。此外,它使代码更长(如果有许多这样的f和许多分析函数)

有没有办法将f的定义从definition.py传递到analysis.py

analysis.py内导入definition.py没有好处,因为我希望能够通过导入不同的模块(例如definition2.py)来更改f的定义,而不再接触analysis.py模块


Tags: 模块函数代码frompyimport标题return
1条回答
网友
1楼 · 发布于 2024-09-29 02:24:42

a comment中所述,最好使用分部:

Python [uses] lexical scope, you are basically asking for dynamic scope. The best way would be to pass the function as an argument. You can simply partially apply f once and then work with that.

例如:

from functools import partial
from definition import f

def actor2(function, x):  # "factor" without the "f" ;)
    return 2*function(x)

factor2 = partial(actor2, f)
>>> factor2(3)
18
>>> factor2  # Also here's the repr, which you wouldn't get if you used a lambda
functools.partial(<function actor2 at 0x...>, <function f at 0x...>)

胡安帕还说:

The other alternative is to use a class where you provide f to the constructor and use it as an instance attribute.

如果你想在课堂上做更多的事情,这是一个很好的选择。否则就太过分了,比如Jack Diederich said

The signature of "this shouldn't be a class" is that it has two methods, one of which is __init__. [...] If you find that you're always passing the same first argument to that function, hey, standard library has a thing for that, functools.partial.

相关问题 更多 >