2
我正在处理嵌套函数有4级嵌套的Python代码。你可以看到下面的例子:如何避免嵌套函数的多级嵌入
class TestClass:
def __init__(self):
pass
def calculate(self, x, y):
results = []
result = None
context = API.send_request('get_context')
if context['result'] == 'ok':
result = context['data']
# Some more actions here
def _is_valid_variable(variable):
if (variable > 0 and
variable % 2 == 0 and
variable < 10):
return True
return False
def _format_data(data):
formatted_data = None
def _extract_time(line):
time = None
if line:
time = line.split('|')[-1]
return time
if data:
for line in data.split('\n'):
formatted_data += '[DEBUG] [{0}] {1}'.format(_extract_time(line), line.split('|')[1])
return formatted_data
return results
在这个例子中只有3个层次,但想法是相同的。
构建此类代码的更好方法是什么?
将所有闭包/内部函数放在父函数的开始处不要混合代码更好吗?
P.S.我不想把这些功能放到班级的水平上,只要他们实际上与班级没有关系,而只与他们的家长功能有关。
[*“Flat比嵌套更好。”*](https://www.python.org/dev/peps/pep-0020/)您的嵌套函数似乎不需要闭包,根本不需要嵌套。 – jonrsharpe
^- +1,我看不到任何你需要“嵌套”功能的原因,简单的类方法或staticmethod会做得很好。不要让你的代码复杂化。 – Anzel
如果函数是在一个函数内部定义的,那么每次函数运行时_redefined。这会让你的功能变慢,没有理由。 – RemcoGerlich