先贴两篇python的PEP,如下:PEP 484 -- Type Hintswww.python.orgPEP 526 -- Syntax for Variable Annotationswww.python.org
比较长,我也没有一行一行的啃。其中表达的大概意思是,这是新的python增强语法,提供了一种变量的注释方式,比如 a:int = 10,表明该变量是int类型,但是只是一种注释,并没有强制,不知以后是否会强制类型。而且这个注释可以是表达式、变量、常量等,比如可以写出如下代码:
title:"this is article title" = "A股很牛"
password:print("密码要保密,不能打印出来") = "123123"
n:int = 10
测试了下,似乎是从python3.6开始支持这个语法。
关于break越级跳出,我总结了四种方式来实现,下面一一说明。使用变量,通过定义变量实现,类似如下的方式:
breaker = False #our mighty loop exiter!
while True:
while True:
if conditionMet:
#insert code here...
breaker = True
break
if breaker: # the interesting part!
break # <利用try except,比如:
class GetOutOfLoop(Exception):
pass
try:
while True:
isok= False
while True:
if True:
raise GetOutOfLoop
except GetOutOfLoop:
pass高端点,用contextmanager来捕获异常,比如:
from contextlib import contextmanager
@contextmanager
def nested_break():
class GetOutOfLoop(Exception):
pass
try:
yield GetOutOfLoop
except GetOutOfLoop:
pass
with nested_break() as mylabel:
while True:
print("current state")
while True:
ok = input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": raise mylabel
if ok == "n" or ok == "N": break
print("more processing")使用goto,虽然python不支持goto,但有人开发了goto的库,如下:https://github.com/snoack/python-gotogithub.com
利用它可以实现goto用法。