Skip to main content
 首页 » 编程设计

python之如何使用另一个python文件函数

2025年05月04日17sharpest

由于我是 Python 世界的新手,今天我想问你关于使用另一个 Python 文件的函数的最佳方法。

让我们举个例子:

- app/ 
  - __init__.py 
  - helpers/ 
    - __init__.py 
    - myhelper.py  
- run.py 

运行.py

import app 
app.setname("helloworld") 
app.run() 

app/__init__.py

def setname(fname): 
    global name 
    name = fname 
 
def run(): 
    import helpers.myhelper as my_helper 
    my_helper.function() 

app/helpers/myhelper.py

from .. import name 
 
def function: 
    return "hello world ! "+name 

我的问题:在函数中间使用导入是否清楚,因为我不能在顶部使用它?

像这样使用全局变量是一种好方法吗?如您所知,我的案例中有多个全局变量等,这就是我制作东西的方式。

有什么建议吗?

请您参考如下方法:

PEP8 Python 代码风格的通用标准指出:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

所以不,在函数中间或代码顶部以外的任何地方进行导入都不是明确的。

另请注意,name 可能不是变量/函数名称的糟糕选择,因为它是一个类似于 list、def、dict 的词,一个可能与用于的词冲突的“保留关键字” Python 中的其他内容。 PEP8建议使用同义词/替代词(在这种情况下我会这样做),或者附加下划线:name_

NB 有一些用例需要在函数内部导入以避免循环导入、作用域等。这些可以包括测试、Flask webapps,但这些是特定的用例,应该遵循从另一个模块访问函数的一般情况PEP 除非必要。然而,通常在这些情况下会出现此类进口,因此更加清晰。