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