【发布时间】:2020-04-07 15:06:47
【问题描述】:
我注意到在我的函数中,我的函数的开头和底部有很多类似的代码行,例如:
def foo1():
print('start')
print('of ')
print('a code')
'''
a lot of other code for the foo1
'''
print('end')
print('of')
print('the code')
def foo2():
print('start')
print('of ')
print('a code')
'''
a lot of other code for the foo2
'''
print('end')
print('of')
print('the code')
我可以将相似的部分放在不同的方法中,如下所示:
def foo_init():
print('start')
print('of ')
print('a code')
def foo_end():
print('end')
print('of')
print('the code')
def foo1():
foo_init()
'''
a lot of other code for the foo1
'''
foo_end():
def foo2():
foo_init()
'''
a lot of the other for the foo1
'''
foo_end():
所以我想知道,是否有更好/更智能的方法,也许是使用类继承或 for 循环?
【问题讨论】:
标签: python python-3.x python-2.7