作者hl4 (Minimi)
看板Python
标题Re: [问题] 怎麽用 Python 写出 switch 的功能?
时间Thu Oct 19 23:41:30 2017
曾经看过有人用 decorator 来写这类功能,就凭印象写写看。
https://gist.github.com/zack1030/505a449678022981f7c384e9b0bde9aa
# 分别对应 init1, init2, init3 的结果
result = [True, False, False]
def init1(func):
def init(*args, **kwargs):
print('init1')
success = result[0] and func(*args, **kwargs)
if not success:
print('release1')
return success
return init
def init2(func):
def init(*args, **kwargs):
print('init2')
success = result[1] and func(*args, **kwargs)
if not success:
print('release2')
return success
return init
@init1
@init2
def init3():
print('init3')
if not result[2]:
print('release3')
return result[2]
def main():
if init3():
print('init success')
if __name__=='__main__':
main()
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 122.116.133.214
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1508427695.A.EEA.html