有时在编写python软件时,我最终会遇到这样的情况:我不确定是将函数与子函数一起使用,还是仅使用类。在这种情况下,我有一系列不同的输入,我想对它们进行一些变换然后产生不同的输出。我不太关心从输入到输出过程中产生的任何变量。所以从这个意义上说,它应该是一个简单的函数,而不是一个类。但在这些情况下,它也涉及到相当复杂的一系列操作,通常需要子函数,这些子函数只在将输入转换为输出的过程中有用,而不是在任何更一般的意义上。
在一天结束的时候,我通常只是想用
来调用它output = my_function(input)
所以我可以输入
def my_function(input):
def subfunc1(blah):
return blah1output
def subfunc2(blah):
return blah2output
#lots of complex code here that calls subfunc1 and subfunc2
return output
但是同事X可能会说,哇,这看起来像一个相当复杂的函数,你应该使用一个类!或者我可以这样做
class my_function(object):
def __new__(self, input):
#lots of complex code here that calls subfunc1 and subfunc2
return output
@staticmethod
def subfunc1(blah):
return blah1output
@staticmethod
def subfunc2(blah):
return blah2output
但是,这似乎是一个奇怪的使用类,因为我并不真正关心创建和维护类的实例。
在这里使用类的一个主要优点是可以更容易地测试subfunc1和subfunc2
,这可能是使用类的充分理由。
然而,由于我仍然是编程新手,有人可以建议生产环境的最佳解决方案和/或通常最python化的解决方案吗?
@wwii的评论是正确的答案。
详细说明一下,您的直觉是正确的,创建一个将作为单例运行的类可能不是python的-模块是实现这一目标的首选方式(这里是编程常见问题中的一个间接引用)。
您还正确地认为,能够测试子函数是很好的。将它们从函数体中取出的另一个原因是,Python作为一种解释型语言,在每次调用外部函数时都会在内部重建子函数。
Benjamin Gleitzman辉煌的howdoi模块(链接到他的github repo)是一个很好的例子,说明如何将复杂的问题分解成小的,非常可读的部分——遵循PEP 8的哲学,"扁平比嵌套好"one_answers"简单比复杂好"
编辑
下面是一个简单模块的示例(python模块教程),它可以掩盖内部函数。结构为:
mymodule
|____
|___ __init__.py
|___ submodule.py
in __init__.py
:
"""
This docstring shows up when someone does `help(mymodule)`.
"""
from submodule import my_function
in submodule.py
:
def _subfunc1(x):
"""A preceding underscore signals to the reader that it's an internal function."""
return x + 1
def _subfunc2(x):
return x * 2
def my_function(x):
"""Yours will be cooler."""
return _subfunc1(x) * _subfunc2(x)
使用它:
>>> import mymodule
>>> result = mymodule.my_function(5)
>>>
>>> # But internal functions (not imported) won't be visible...
>>> mymodule._subfunc1(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '_subfunc1'