Re: [問題] 怎麼用 Python 寫出 switch 的功能?

作者: hl4 (Zec)   2017-10-19 23:41:30
曾經看過有人用 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()

Links booklink

Contact Us: admin [ a t ] ucptt.com