更新时间:2023-11-26 11:07:22
另一种方法是制作一个 util
package 并将您的函数拆分为该包中的不同模块.软件包的基础知识:创建一个目录(其名称将为软件包名称)并在其中放置一个特殊文件,即 __ init __.py
文件.该可以包含代码,但是对于基本的软件包组织而言,它可以是一个空文件.
Another approach is to make a util
package and split up your functions into different modules within that package. The basics of packages: make a directory (whose name will be the package name) and put a special file in it, the __init__.py
file. This can contain code, but for the basic package organization, it can be an empty file.
my_package/
__init__.py
module1.py/
modle2.py/
...
module3.py
假设您位于工作目录中
mkdir util
touch util/__init__.py
然后在您的 util
目录中,创建 calc_funcs.py
Then inside your util
directory, make calc_funcs.py
def add(a,b):
return a + b
def sub(a,b):
return a -b
和 format_funcs.py
:
def cap(string):
return string.title()
def lower(string):
return string.lower()
现在,从您的工作目录中,您可以执行以下操作:
And now, from your working directory, you can do things like the following:
>>> from util import calc_funcs
>>> calc_funcs.add(1,3)
4
>>> from util.format_funcs import cap
>>> cap("the quick brown fox jumped over the lazy dog")
'The Quick Brown Fox Jumped Over The Lazy Dog'
但是,请注意,如果我们重新启动解释器会话,则:
Notice, though, if we restart the interpreter session:
>>> import util
>>> util.format_funcs.cap("i should've been a book")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'util' has no attribute 'format_funcs'
这就是 __ init __.py
的目的!
在 __ init __.py
中,添加以下内容:
import util.calc_funcs, util.format_funcs
现在,再次重新启动解释器:
Now, restart the interpreter again:
>>> import util
>>> util.calc_funcs.add('1','2')
'12'
>>> util.format_funcs.lower("I DON'T KNOW WHAT I'M YELLING ABOUT")
"i don't know what i'm yelling about"
是的!我们可以通过易于导入的方式灵活控制名称空间!基本上, __ init __.py
与类定义中的 __ init __
方法类似.
Yay! We have flexible control over our namespaces with easy importing! Basically, the __init__.py
plays an analogous role to the __init__
method in a class definition.