°´Õ½Úä¯ÀÀÎĵµ:
Ë÷ÒýºÍ±í¸ñ:
Python ½Ì³Ì ¡ª Python 3.11.0b3 Îĵµ
Python Ä£¿éË÷Òý ¡ª Python 3.11.0b3 Îĵµ
Python ÓïÑԲο¼ÊÖ²á ¡ª Python 3.11.0b3 Îĵµ
?????ÄÚÖú¯Êý ¡ª Python 3.11.0b3 Îĵµ
Python ±ê×¼¿â ¡ª Python 3.11.0b3 Îĵµ
À©Õ¹ºÍǶÈë Python ½âÊÍÆ÷ ¡ª Python 3.11.0b3 Îĵµ
ÄÚÖú¯Êý?
Python ½âÊÍÆ÷ÄÚÖÃÁ˺ܶຯÊýºÍÀàÐÍ,ÈκÎʱºò¶¼ÄÜʹÓá£ÒÔÏ°´×Öĸ˳Ðò¸ø³öÁÐ±í¡£
Python ÓïÑԲο¼ÊÖ²á ¡ª Python 3.11.0b3 Îĵµ
Python ÓïÑԲο¼ÊÖ²á?ÃèÊöÁË Python ÓïÑԵľßÌåÓï·¨ºÍÓïÒå,Õâ·Ý¿â²Î¿¼Ôò½éÉÜÁËÓë Python һͬ·¢Ðеıê×¼¿â¡£Ëü»¹ÃèÊöÁËͨ³£°üº¬ÔÚ Python ·¢ÐаæÖеÄһЩ¿ÉÑ¡×é¼þ¡£
Python ±ê×¼¿â·Ç³£ÅÓ´ó,ËùÌṩµÄ×é¼þÉæ¼°·¶Î§Ê®·Ö¹ã·º,ÕýÈçÒÔÏÂÄÚÈÝĿ¼ËùÏÔʾµÄ¡£Õâ¸ö¿â°üº¬Á˶à¸öÄÚÖÃÄ£¿é (ÒÔ C ±àд),Python ³ÌÐòÔ±±ØÐëÒÀ¿¿ËüÃÇÀ´ÊµÏÖϵͳ¼¶¹¦ÄÜ,ÀýÈçÎļþ I/O,´ËÍ⻹ÓдóÁ¿ÒÔ Python ±àдµÄÄ£¿é,ÌṩÁËÈÕ³£±à³ÌÖÐÐí¶àÎÊÌâµÄ±ê×¼½â¾ö·½°¸¡£ÆäÖÐÓÐЩģ¿é¾¹ýרÃÅÉè¼Æ,ͨ¹ý½«Ìض¨Æ½Ì¨¹¦ÄܳéÏó»¯ÎªÆ½Ì¨ÖÐÁ¢µÄ API À´¹ÄÀøºÍ¼ÓÇ¿ Python ³ÌÐòµÄ¿ÉÒÆÖ²ÐÔ¡£
Windows °æ±¾µÄ Python °²×°³ÌÐòͨ³£°üº¬Õû¸ö±ê×¼¿â,ÍùÍù»¹°üº¬Ðí¶à¶îÍâ×é¼þ¡£¶ÔÓÚÀà Unix ²Ù×÷ϵͳ,Python ͨ³£»á·Ö³ÉһϵÁеÄÈí¼þ°ü,Òò´Ë¿ÉÄÜÐèҪʹÓòÙ×÷ϵͳËùÌṩµÄ°ü¹ÜÀí¹¤¾ßÀ´»ñÈ¡²¿·Ö»òÈ«²¿¿ÉÑ¡×é¼þ¡£
ÔÚÕâ¸ö±ê×¼¿âÒÔÍ⻹´æÔÚ³ÉǧÉÏÍò²¢ÇÒ²»¶ÏÔö¼ÓµÄÆäËû×é¼þ (´Óµ¥¶ÀµÄ³ÌÐò¡¢Ä£¿é¡¢Èí¼þ°üÖ±µ½ÍêÕûµÄÓ¦Óÿª·¢¿ò¼Ü),·ÃÎÊ?Python °üË÷Òý?¼´¿É»ñÈ¡ÕâЩµÚÈý·½°ü¡£
abs(x)
·µ»ØÒ»¸öÊýµÄ¾ø¶ÔÖµ¡£ ²ÎÊý¿ÉÒÔÊÇÕûÊý¡¢¸¡µãÊý»òÈκÎʵÏÖÁË?__abs__() ?µÄ¶ÔÏó¡£ Èç¹û²ÎÊýÊÇÒ»¸ö¸´Êý,Ôò·µ»ØËüµÄÄ£¡£
aiter(async_iterable)
·µ»Ø?asynchronous iterable?µÄ?asynchronous iterator?¡£Ï൱ÓÚµ÷ÓÃ?x.__aiter__() ¡£
×¢Òâ:Óë?iter()?²»Í¬,aiter()?ûÓÐÁ½¸ö²ÎÊýµÄ°æ±¾¡£
3.10 а湦ÄÜ.
all(iterable)
Èç¹û?iterable?µÄËùÓÐÔªËؾùΪÕæÖµ(»ò¿Éµü´ú¶ÔÏóΪ¿Õ)Ôò·µ»Ø?True ?¡£ µÈ¼ÛÓÚ:
def all(iterable):
for element in iterable:
if not element:
return False
return True
awaitable?anext(async_iterator[,?default])
µ±½øÈë await ״̬ʱ,´Ó¸ø¶¨?asynchronous iterator?·µ»ØÏÂÒ»Êý¾ÝÏî,µü´úÍê±ÏÔò·µ»Ø?default¡£
ÕâÊÇÄÚÖú¯Êý?next()?µÄÒì²½°æ±¾,ÀàËÆÓÚ:
µ÷ÓÃ?async_iterator?µÄ?__anext__()?·½·¨,·µ»ØÒ»¸ö?awaitable¡£µÈ´ý·µ»Øµü´úÆ÷µÄÏÂÒ»¸öÖµ¡£ÈôÓиø³ö?default,ÔòÔÚµü´úÍê±Ïºó»á·µ»Ø¸ø³öµÄÖµ,·ñÔò»á´¥·¢?StopAsyncIteration¡£
3.10 а湦ÄÜ.
any(iterable)
Èç¹û?iterable?µÄÈÎÒ»ÔªËØΪÕæÖµÔò·µ»Ø?True ¡£ Èç¹û¿Éµü´ú¶ÔÏóΪ¿Õ,·µ»Ø?False ¡£ µÈ¼ÛÓÚ:
def any(iterable):
for element in iterable:
if element:
return True
return False
ascii(object)
Óë?repr()?ÀàËÆ,·µ»ØÒ»¸ö×Ö·û´®,±íʾ¶ÔÏóµÄ¿É´òÓ¡ÐÎʽ,µ«ÔÚ?repr()?·µ»ØµÄ×Ö·û´®ÖÐ,·Ç ASCII ×Ö·û»áÓÃ?\x ¡¢\u ?ºÍ?\U ?½øÐÐתÒå¡£Éú³ÉµÄ×Ö·û´®ÀàËÆÓÚ Python 2 ÖÐ?repr()?µÄ·µ»Ø½á¹û¡£
bin(x)
½«ÕûÊýת±äΪÒÔ¡°0b¡±Ç°×ºµÄ¶þ½øÖÆ×Ö·û´®¡£½á¹ûÊÇÒ»¸öºÏ·¨µÄ Python ±í´ïʽ¡£Èç¹û?x?²»ÊÇ Python µÄ?int?¶ÔÏó,Ëü±ØÐ붨Òå?__index__() ?·½·¨,ÒԱ㷵»ØÕûÊýÖµ¡£ÏÂÃæÊÇһЩÀý×Ó:
>>>
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
ÈôÒª¿ØÖÆÊÇ·ñÏÔʾǰ׺¡°0b¡±,¿ÉÒÔ²ÉÓÃÒÔÏÂÁ½ÖÖ·½°¸:
>>>
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
Áí¼û?format()?»ñÈ¡¸ü¶àÐÅÏ¢¡£
class?bool([x])
·µ»Ø²¼¶ûÖµ,True ?»ò?False ¡£x?Óñê×¼µÄ?ÕæÖµ²âÊÔ¹ý³Ì?½øÐÐת»»¡£Èç¹û?x?Ϊ False »òÊ¡ÂÔ,Ôò·µ»Ø?False ;·ñÔò·µ»Ø?True ¡£?bool?ÀàÊÇ?int?µÄ×ÓÀà(¼û?Êý×ÖÀàÐÍ --- int, float, complex?)¡£Ëü²»ÄÜÔÙ±»¼Ì³Ð¡£ËüΨһµÄʵÀý¾ÍÊÇ?False ?ºÍ?True ?(²ÎÔÄ?²¼¶ûÖµ?)¡£
ÔÚ 3.7 °æ¸ü¸Ä:?x?ÏÖÔÚÖ»ÄÜ×÷ΪλÖòÎÊý¡£
breakpoint(*args,?**kws)
´Ëº¯Êý»áÔÚµ÷ÓÃʱ½«ÄãÏÝÈëµ÷ÊÔÆ÷ÖС£¾ßÌåÀ´Ëµ,Ëüµ÷ÓÃ?sys.breakpointhook()?,Ö±½Ó´«µÝ?args ?ºÍ?kws ?¡£Ä¬ÈÏÇé¿öÏÂ,?sys.breakpointhook() ?µ÷ÓÃ?pdb.set_trace()?ÇÒûÓвÎÊý¡£ÔÚÕâÖÖÇé¿öÏÂ,Ëü´¿´âÊÇÒ»¸ö±ãÀûº¯Êý,Òò´ËÄú²»±ØÏÔʽµ¼Èë?pdb?ÇÒ¼üÈ뾡¿ÉÄÜÉٵĴúÂë¼´¿É½øÈëµ÷ÊÔÆ÷¡£µ«ÊÇ,?sys.breakpointhook()?¿ÉÒÔÉèÖÃΪÆäËûһЩº¯Êý²¢±»?breakpoint()?×Ô¶¯µ÷ÓÃ,ÒÔÔÊÐí½øÈëÄãÏëÓõĵ÷ÊÔÆ÷¡£
Òý·¢Ò»¸ö?Éó¼Æʼþ?builtins.breakpoint ?²¢¸½´ø²ÎÊý?breakpointhook ¡£
3.7 а湦ÄÜ.
class?bytearray([source[,?encoding[,?errors]]])
·µ»ØÒ»¸öÐ嵀 bytes Êý×é¡£?bytearray?ÀàÊÇÒ»¸ö¿É±äÐòÁÐ,°üº¬·¶Î§Îª 0 <= x < 256 µÄÕûÊý¡£ËüÓпɱäÐòÁд󲿷ֳ£¼ûµÄ·½·¨,¼û?¿É±äÐòÁÐÀàÐÍ?µÄÃèÊö;ͬʱÓÐ?bytes?ÀàÐ͵Ĵ󲿷ַ½·¨,²Î¼û?bytes ºÍ bytearray ²Ù×÷¡£
¿ÉÑ¡ÐβÎ?source?¿ÉÒÔÓò»Í¬µÄ·½Ê½À´³õʼ»¯Êý×é:
-
Èç¹ûÊÇÒ»¸ö?string,Äú±ØÐëÌṩ?encoding?²ÎÊý(errors?²ÎÊýÈÔÊÇ¿ÉÑ¡µÄ);bytearray()?»áʹÓÃ?str.encode()?·½·¨À´½« string ת±ä³É bytes¡£ -
Èç¹ûÊÇÒ»¸ö?integer,»á³õʼ»¯´óСΪ¸ÃÊý×ÖµÄÊý×é,²¢Ê¹Óà null ×Ö½ÚÌî³ä¡£ -
Èç¹ûÊÇÒ»¸ö×ñÑ?»º³åÇø½Ó¿Ú?µÄ¶ÔÏó,¸Ã¶ÔÏóµÄÖ»¶Á»º³åÇø½«±»ÓÃÀ´³õʼ»¯×Ö½ÚÊý×é¡£ -
Èç¹ûÊÇÒ»¸ö?iterable?¿Éµü´ú¶ÔÏó,ËüµÄÔªËصķ¶Î§±ØÐëÊÇ?0?<=?x?<?256 ?µÄÕûÊý,Ëü»á±»ÓÃ×÷Êý×éµÄ³õʼÄÚÈÝ¡£
Èç¹ûûÓÐʵ²Î,Ôò´´½¨´óСΪ 0 µÄÊý×é¡£
Áí¼û?¶þ½øÖÆÐòÁÐÀàÐÍ --- bytes, bytearray, memoryview?ºÍ?bytearray ¶ÔÏó¡£
class?bytes([source[,?encoding[,?errors]]])
·µ»ØÒ»¸öеġ°bytes¡±¶ÔÏó,ÕâÊÇÒ»¸ö²»¿É±äÐòÁÐ,°üº¬·¶Î§Îª?0?<=?x?<?256 ?µÄÕûÊý¡£bytes?ÊÇ?bytearray?µÄ²»¿É±ä°æ±¾¡ª¡ª´øÓÐͬÑù²»¸Ä±äÐòÁеķ½·¨,Ö§³ÖͬÑùµÄË÷Òý¡¢ÇÐƬ²Ù×÷¡£
Òò´Ë,¹¹Ô캯ÊýµÄʵ²ÎºÍ?bytearray()?Ïàͬ¡£
×Ö½Ú¶ÔÏ󻹿ÉÒÔÓÃ×ÖÃæÖµ´´½¨,²Î¼û?×Ö·û´®Óë×Ö½Ú´®×ÖÃæÖµ¡£
Áí¼û?¶þ½øÖÆÐòÁÐÀàÐÍ --- bytes, bytearray, memoryview,bytes ¶ÔÏó?ºÍ?bytes ºÍ bytearray ²Ù×÷¡£
callable(object)
Èç¹û²ÎÊý?object?Êǿɵ÷Óõľͷµ»Ø?True,·ñÔò·µ»Ø?False¡£ Èç¹û·µ»Ø?True ,µ÷ÓÃÈÔ¿ÉÄÜʧ°Ü,µ«Èç¹û·µ»Ø?False ,Ôòµ÷ÓÃ?object?½«¿Ï¶¨²»»á³É¹¦¡£ Çë×¢ÒâÀàÊǿɵ÷ÓõÄ(µ÷ÓÃÀཫ·µ»ØÒ»¸öеÄʵÀý);Èç¹ûʵÀýËùÊôµÄÀàÓÐ?__call__() ?ÔòËü¾ÍÊǿɵ÷Óõġ£
3.2 а湦ÄÜ:?Õâ¸öº¯ÊýÒ»¿ªÊ¼ÔÚ Python 3.0 ±»ÒƳýÁË,µ«ÔÚ Python 3.2 ±»ÖØмÓÈë¡£
chr(i)
·µ»Ø Unicode ÂëλΪÕûÊý?i?µÄ×Ö·ûµÄ×Ö·û´®¸ñʽ¡£ÀýÈç,chr(97) ?·µ»Ø×Ö·û´®?'a' ,chr(8364) ?·µ»Ø×Ö·û´®?'€' ¡£ÕâÊÇ?ord()?µÄÄ溯Êý¡£
ʵ²ÎµÄºÏ·¨·¶Î§ÊÇ 0 µ½ 1,114,111(16 ½øÖƱíʾÊÇ 0x10FFFF)¡£Èç¹û?i?³¬¹ýÕâ¸ö·¶Î§,»á´¥·¢?ValueError?Òì³£¡£
@classmethod
°ÑÒ»¸ö·½·¨·â×°³ÉÀà·½·¨¡£
Àà·½·¨Òþº¬µÄµÚÒ»¸ö²ÎÊý¾ÍÊÇÀà,¾ÍÏñʵÀý·½·¨½ÓÊÕʵÀý×÷Ϊ²ÎÊýÒ»Ñù¡£ÒªÉùÃ÷Ò»¸öÀà·½·¨,°´¹ßÀýÇëʹÓÃÒÔÏ·½°¸:
class C:
@classmethod
def f(cls, arg1, arg2): ...
@classmethod ?ÕâÑùµÄÐÎʽ³ÆΪº¯ÊýµÄ?decorator?-- ÏêÇé²ÎÔÄ?º¯Êý¶¨Òå¡£
Àà·½·¨µÄµ÷ÓÿÉÒÔÔÚÀàÉϽøÐÐ (ÀýÈç?C.f() ) Ò²¿ÉÒÔÔÚʵÀýÉϽøÐÐ (ÀýÈç?C().f() )¡£ ÆäËùÊôÀàÒÔÍâµÄÀàʵÀý»á±»ºöÂÔ¡£ Èç¹ûÀà·½·¨ÔÚÆäËùÊôÀàµÄÅÉÉúÀàÉϵ÷ÓÃ,Ôò¸ÃÅÉÉúÀà¶ÔÏó»á±»×÷ΪÒþº¬µÄµÚÒ»¸ö²ÎÊý±»´«Èë¡£
Àà·½·¨Óë C++ »ò Java Öеľ²Ì¬·½·¨²»Í¬¡£ Èç¹ûÄãÐèÒªºóÕß,Çë²ÎÔı¾½ÚÖеÄ?staticmethod()¡£ ÓйØÀà·½·¨µÄ¸ü¶àÐÅÏ¢,Çë²ÎÔÄ?±ê×¼ÀàÐͲ㼶½á¹¹¡£
ÔÚ 3.9 °æ¸ü¸Ä:?Àà·½·¨ÏÖÔÚ¿ÉÒÔ°ü×°ÆäËû?ÃèÊöÆ÷?ÀýÈç?property()¡£
ÔÚ 3.10 °æ¸ü¸Ä:?Àà·½·¨ÏÖÔڼ̳ÐÁË·½·¨µÄÊôÐÔ(__module__ ¡¢__name__ ¡¢__qualname__ ¡¢__doc__ ?ºÍ?__annotations__ ),²¢ÓµÓÐÒ»¸öеÄ``__wrapped__`` ÊôÐÔ¡£
ÔÚ 3.11 °æ¸ü¸Ä:?Class methods can no longer wrap other?descriptors?such as?property().
compile(source,?filename,?mode,?flags=0,?dont_inherit=False,?optimize=-?1)
½«?source?±àÒë³É´úÂë»ò AST ¶ÔÏó¡£´úÂë¶ÔÏó¿ÉÒÔ±»?exec()?»ò?eval()?Ö´ÐС£source?¿ÉÒÔÊdz£¹æµÄ×Ö·û´®¡¢×Ö½Ú×Ö·û´®,»òÕß AST ¶ÔÏ󡣲μû?ast?Ä£¿éµÄÎĵµÁ˽âÈçºÎʹÓà AST ¶ÔÏó¡£
filename?ʵ²ÎÐèÒªÊÇ´úÂë¶ÁÈ¡µÄÎļþÃû;Èç¹û´úÂë²»ÐèÒª´ÓÎļþÖжÁÈ¡,¿ÉÒÔ´«ÈëһЩ¿É±æʶµÄÖµ(¾³£»áʹÓÃ?'<string>' )¡£
mode?ʵ²ÎÖ¸¶¨Á˱àÒë´úÂë±ØÐëÓõÄģʽ¡£Èç¹û?source?ÊÇÓï¾äÐòÁÐ,¿ÉÒÔÊÇ?'exec' ;Èç¹ûÊǵ¥Ò»±í´ïʽ,¿ÉÒÔÊÇ?'eval' ;Èç¹ûÊǵ¥¸ö½»»¥Ê½Óï¾ä,¿ÉÒÔÊÇ?'single' ¡£(ÔÚ×îºóÒ»ÖÖÇé¿öÏÂ,Èç¹û±í´ïʽִÐнá¹û²»ÊÇ?None ?½«»á±»´òÓ¡³öÀ´¡£)
¿ÉÑ¡²ÎÊý?flags?ºÍ?dont_inherit?¿ØÖÆÓ¦µ±¼¤»îÄĸö?±àÒëÆ÷Ñ¡Ïî?ÒÔ¼°Ó¦µ±ÔÊÐíÄĸö?future ÌØÐÔ¡£ Èç¹ûÁ½Õ߶¼Î´Ìṩ (»ò¶¼ÎªÁã) Ôò´úÂë»áÓ¦ÓÃÓëµ÷ÓÃ?compile()?µÄ´úÂëÏàͬµÄÆì±êÀ´±àÒë¡£ Èç¹û¸ø³öÁË?flags?²ÎÊý¶øδ¸ø³ö?dont_inherit?(»òÕßΪÁã) Ôò»áÔÚÎÞÂÛÈçºÎ¶¼½«±»Ê¹ÓõÄÆì±êÖ®Í⻹»á¶îÍâʹÓÃ?flags?²ÎÊýËùÖ¸¶¨µÄ±àÒëÆ÷Ñ¡ÏîºÍ future Óï¾ä¡£ Èç¹û?dont_inherit?Ϊ·ÇÁãÕûÊý,ÔòֻʹÓÃ?flags?²ÎÊý -- ÍâΧ´úÂëÖеÄÆì±ê (future ÌØÐԺͱàÒëÆ÷Ñ¡Ïî) »á±»ºöÂÔ¡£
±àÒëÆ÷Ñ¡ÏîºÍ future Óï¾äÊÇÓɱÈÌØλÀ´Ö¸Ã÷µÄ¡£ ±ÈÌØλ¿ÉÒÔͨ¹ýÒ»Æð°´Î» OR À´Ö¸Ã÷¶à¸öÑ¡Ïî¡£ Ö¸Ã÷Ìض¨ future ÌØÐÔËùÐèµÄ±ÈÌØλ¿ÉÒÔÔÚ?__future__?Ä£¿éµÄ?_Feature ?ʵÀýµÄ?compiler_flag ?ÊôÐÔÖÐÕÒµ½¡£?±àÒëÆ÷Æì±ê?¿ÉÒÔÔÚ?ast?Ä£¿éÖвéÕÒ´øÓÐ?PyCF_ ?ǰ׺µÄÃû³Æ¡£
optimize?ʵ²ÎÖ¸¶¨±àÒëÆ÷µÄÓÅ»¯¼¶±ð;ĬÈÏÖµ?-1 ?Ñ¡ÔñÓë½âÊÍÆ÷µÄ?-O?Ñ¡ÏîÏàͬµÄÓÅ»¯¼¶±ð¡£ÏÔʽ¼¶±ðΪ?0 ?(ûÓÐÓÅ»¯;__debug__ ?ΪÕæ)¡¢1 ?(¶ÏÑÔ±»É¾³ý,?__debug__ ?Ϊ¼Ù)»ò?2 ?(Îĵµ×Ö·û´®Ò²±»É¾³ý)¡£
Èç¹û±àÒëµÄÔ´Âë²»ºÏ·¨,´Ëº¯Êý»á´¥·¢?SyntaxError?Òì³£;Èç¹ûÔ´Âë°üº¬ null ×Ö½Ú,Ôò»á´¥·¢?ValueError?Òì³£¡£
Èç¹ûÄúÏë·ÖÎö Python ´úÂëµÄ AST ±íʾ,Çë²ÎÔÄ?ast.parse()¡£
Òý·¢Ò»¸ö?Éó¼Æʼþ?compile ?¸½´ø²ÎÊý?source ,?filename ¡£
±¸×¢
ÔÚ?'single' ?»ò?'eval' ?ģʽ±àÒë¶àÐдúÂë×Ö·û´®Ê±,ÊäÈë±ØÐëÒÔÖÁÉÙÒ»¸ö»»Ðзû½áβ¡£ Õâʹ?code?Ä£¿é¸üÈÝÒ×¼ì²âÓï¾äµÄÍêÕûÐÔ¡£
¾¯¸æ
ÔÚ½«×ã¹»´ó»òÕß×ã¹»¸´ÔÓµÄ×Ö·û´®±àÒë³É AST ¶ÔÏóʱ,Python ½âÊÍÆ÷ÓпÉÄÜÒòΪ Python AST ±àÒëÆ÷µÄÕ»Éî¶ÈÏÞÖƶø±ÀÀ£¡£
ÔÚ 3.2 °æ¸ü¸Ä:?Windows ºÍ Mac µÄ»»Ðзû¾ù¿ÉʹÓ᣶øÇÒÔÚ?'exec' ?ģʽϵÄÊäÈë²»±ØÔÙÒÔ»»Ðзû½áβÁË¡£ÁíÔö¼ÓÁË?optimize?²ÎÊý¡£
ÔÚ 3.5 °æ¸ü¸Ä:?֮ǰ?source?Öаüº¬ null ×ֽڵĻ°»á´¥·¢?TypeError?Òì³£¡£
3.8 а湦ÄÜ:?ast.PyCF_ALLOW_TOP_LEVEL_AWAIT ?ÏÖÔÚ¿ÉÔÚÆì±êÖд«ÈëÒÔÆôÓöÔ×î¸ß²ã¼¶?await ,?async?for ?ºÍ?async?with ?µÄÖ§³Ö¡£
class?complex([real[,?imag]])
·µ»ØֵΪ?real?+?imag*1j µÄ¸´Êý,»ò½«×Ö·û´®»òÊý×Öת»»Îª¸´Êý¡£Èç¹ûµÚÒ»¸öÐβÎÊÇ×Ö·û´®,ÔòËü±»½âÊÍΪһ¸ö¸´Êý,²¢ÇÒº¯Êýµ÷ÓÃʱ±ØÐëûÓеڶþ¸öÐβΡ£µÚ¶þ¸öÐββ»ÄÜÊÇ×Ö·û´®¡£Ã¿¸öʵ²Î¶¼¿ÉÒÔÊÇÈÎÒâµÄÊýÖµÀàÐÍ(°üÀ¨¸´Êý)¡£Èç¹ûÊ¡ÂÔÁË?imag,ÔòĬÈÏֵΪÁã,¹¹Ô캯Êý»áÏñ?int?ºÍ?float?Ò»Ñù½øÐÐÊýֵת»»¡£Èç¹ûÁ½¸öʵ²Î¶¼Ê¡ÂÔ,Ôò·µ»Ø?0j ¡£
¶ÔÓÚÒ»¸öÆÕͨ Python ¶ÔÏó?x ,complex(x) ?»áίÍиø?x.__complex__() ¡£ Èç¹û?__complex__() ?䶨ÒåÔò½«»ØÍËÖÁ?__float__() ¡£ Èç¹û?__float__() ?䶨ÒåÔò½«»ØÍËÖÁ?__index__() ¡£
±¸×¢
µ±´Ó×Ö·û´®×ª»»Ê±,×Ö·û´®ÔÚ?+ ?»ò?- ?µÄÖÜΧ±ØÐë²»ÄÜÓпոñ¡£ÀýÈç?complex('1+2j') ?ÊǺϷ¨µÄ,µ«?complex('1?+?2j') ?»á´¥·¢?ValueError?Òì³£¡£
Êý×ÖÀàÐÍ --- int, float, complex?ÃèÊöÁ˸´ÊýÀàÐÍ¡£
ÔÚ 3.6 °æ¸ü¸Ä:?Äú¿ÉÒÔʹÓÃÏ»®Ïß½«´úÂëÎÄ×ÖÖеÄÊý×Ö½øÐзÖ×é¡£
ÔÚ 3.8 °æ¸ü¸Ä:?Èç¹û?__complex__() ?ºÍ?__float__() ?䶨ÒåÔò»ØÍËÖÁ?__index__() ¡£
delattr(object,?name)
setattr()?Ïà¹ØµÄº¯Êý¡£Êµ²ÎÊÇÒ»¸ö¶ÔÏóºÍÒ»¸ö×Ö·û´®¡£¸Ã×Ö·û´®±ØÐëÊǶÔÏóµÄij¸öÊôÐÔ¡£Èç¹û¶ÔÏóÔÊÐí,¸Ãº¯Êý½«É¾³ýÖ¸¶¨µÄÊôÐÔ¡£ÀýÈç?delattr(x,?'foobar') ?µÈ¼ÛÓÚ?del?x.foobar ?¡£
class?dict(**kwarg)
class?dict(mapping,?**kwarg)
class?dict(iterable,?**kwarg)
´´½¨Ò»¸öеÄ×ֵ䡣dict?¶ÔÏóÊÇÒ»¸ö×ÖµäÀà¡£²Î¼û?dict?ºÍ?Ó³ÉäÀàÐÍ --- dict?Á˽âÕâ¸öÀà¡£
ÆäËûÈÝÆ÷ÀàÐÍ,Çë²Î¼ûÄÚÖõÄ?list¡¢set?ºÍ?tuple?Àà,ÒÔ¼°?collections?Ä£¿é¡£
dir([object])
Èç¹ûûÓÐʵ²Î,Ôò·µ»Øµ±Ç°±¾µØ×÷ÓÃÓòÖеÄÃû³ÆÁÐ±í¡£Èç¹ûÓÐʵ²Î,Ëü»á³¢ÊÔ·µ»Ø¸Ã¶ÔÏóµÄÓÐЧÊôÐÔÁÐ±í¡£
Èç¹û¶ÔÏóÓÐÒ»¸öÃûΪ?__dir__() ?µÄ·½·¨,ÄÇô¸Ã·½·¨½«±»µ÷ÓÃ,²¢ÇÒ±ØÐë·µ»ØÒ»¸öÊôÐÔÁÐ±í¡£ÕâÔÊÐíʵÏÖ×Ô¶¨Òå?__getattr__() ?»ò?__getattribute__() ?º¯ÊýµÄ¶ÔÏóÄܹ»×Ô¶¨Òå?dir()?À´±¨¸æËüÃǵÄÊôÐÔ¡£
Èç¹û¶ÔÏóδÌṩ?__dir__() ?·½·¨,¸Ãº¯Êý»á¾¡Á¿´Ó¶ÔÏóµÄ?__dict__?ÊôÐÔºÍÆäÀàÐͶÔÏóÖÐÊÕ¼¯ÐÅÏ¢¡£µÃµ½µÄÁÐ±í²»Ò»¶¨ÊÇÍêÕû,Èç¹û¶ÔÏó´øÓÐ×Ô¶¨Òå?__getattr__() ?·½·¨Ê±,½á¹û¿ÉÄܲ»×¼È·¡£
ĬÈϵÄ?dir()?»úÖƶԲ»Í¬ÀàÐ͵ĶÔÏóÐÐΪ²»Í¬,Ëü»áÊÔͼ·µ»Ø×îÏà¹Ø¶ø²»ÊÇ×îÈ«µÄÐÅÏ¢:
-
Èç¹û¶ÔÏóÊÇÄ£¿é¶ÔÏó,ÔòÁбí°üº¬Ä£¿éµÄÊôÐÔÃû³Æ¡£ -
Èç¹û¶ÔÏóÊÇÀàÐÍ»òÀà¶ÔÏó,ÔòÁбí°üº¬ËüÃǵÄÊôÐÔÃû³Æ,²¢Çҵݹé²éÕÒËùÓлùÀàµÄÊôÐÔ¡£ -
·ñÔò,Áбí°üº¬¶ÔÏóµÄÊôÐÔÃû³Æ,ËüµÄÀàÊôÐÔÃû³Æ,²¢Çҵݹé²éÕÒËüµÄÀàµÄËùÓлùÀàµÄÊôÐÔ¡£
·µ»ØµÄÁÐ±í°´×Öĸ±íÅÅÐò¡£ÀýÈç:
>>>
>>> import struct
>>> dir() # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct) # show the names in the struct module
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__', '__package__',
'_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
±¸×¢
ÒòΪ?dir()?Ö÷ÒªÊÇΪÁ˱ãÓÚÔÚ½»»¥Ê½Ê±Ê¹ÓÃ,ËùÒÔËü»áÊÔͼ·µ»ØÈËÃǸÐÐËȤµÄÃû×Ö¼¯ºÏ,¶ø²»ÊÇÊÔͼ±£Ö¤½á¹ûµÄÑϸñÐÔ»òÒ»ÖÂÐÔ,Ëü¾ßÌåµÄÐÐΪҲ¿ÉÄÜÔÚ²»Í¬°æ±¾Ö®¼ä¸Ä±ä¡£ÀýÈç,µ±Êµ²ÎÊÇÒ»¸öÀàʱ,metaclass µÄÊôÐÔ²»°üº¬ÔÚ½á¹ûÁбíÖС£
divmod(a,?b)
ÒÔÁ½¸ö(·Ç¸´Êý)Êý×ÖΪ²ÎÊý,ÔÚ×÷ÕûÊý³ý·¨Ê±,·µ»ØÉ̺ÍÓàÊý¡£Èô²Ù×÷ÊýΪ»ìºÏÀàÐÍ,ÔòÊÊÓöþ½øÖÆËãÊõÔËËã·ûµÄ¹æÔò¡£¶ÔÓÚÕûÊý¶øÑÔ,½á¹ûÓë?(a?//?b,?a?%?b) ?Ïàͬ¡£¶ÔÓÚ¸¡µãÊýÔò½á¹ûΪ``(q, a % b)``,ÆäÖÐ?q?ͨ³£Îª?math.floor(a?/?b) ,µ«¿ÉÄܱÈËüС 1¡£ÔÚÈκÎÇé¿öÏÂ,q?*?b?+?a?%?b ?¶¼·Ç³£½Ó½ü?a,Èç¹û?a?%?b ?·ÇÁã,Ôò½á¹û·ûºÅÓë?b?Ïàͬ,²¢ÇÒ?0?<=?abs(a?%?b)?<?abs(b) ¡£
enumerate(iterable,?start=0)
·µ»ØÒ»¸öö¾Ù¶ÔÏó¡£iterable?±ØÐëÊÇÒ»¸öÐòÁÐ,»ò?iterator,»òÆäËûÖ§³Öµü´úµÄ¶ÔÏó¡£?enumerate()?·µ»ØµÄµü´úÆ÷µÄ?__next__()?·½·¨·µ»ØÒ»¸öÔª×é,ÀïÃæ°üº¬Ò»¸ö¼ÆÊýÖµ(´Ó?start?¿ªÊ¼,ĬÈÏΪ 0)ºÍͨ¹ýµü´ú?iterable?»ñµÃµÄÖµ¡£
>>>
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
µÈ¼ÛÓÚ:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
eval(expression[,?globals[,?locals]])
ʵ²ÎÊÇÒ»¸ö×Ö·û´®,ÒÔ¼°¿ÉÑ¡µÄ globals ºÍ locals¡£globals?ʵ²Î±ØÐëÊÇÒ»¸ö×ֵ䡣locals?¿ÉÒÔÊÇÈκÎÓ³Éä¶ÔÏó¡£
±í´ïʽ½âÎö²ÎÊý?expression?²¢×÷Ϊ Python ±í´ïʽ½øÐÐÇóÖµ(´Ó¼¼ÊõÉÏ˵ÊÇÒ»¸öÌõ¼þÁбí),²ÉÓÃ?globals?ºÍ?locals?×Öµä×÷Ϊȫ¾ÖºÍ¾Ö²¿ÃüÃû¿Õ¼ä¡£ Èç¹û´æÔÚ?globals?×Öµä,²¢ÇÒ²»°üº¬?__builtins__ ?¼üµÄÖµ,ÔòÔÚ½âÎö?expression?֮ǰ»á²åÈëÒÔ¸Ã×Ö·û´®Îª¼üÒÔ¶ÔÄÚÖÃÄ£¿é?builtins?µÄ×ÖµäµÄÒýÓÃΪֵµÄÏî¡£ ÕâÑù¾Í¿ÉÒÔÔÚ½«?globals?´«¸ø?eval()?֮ǰͨ¹ýÏòÆä´«ÈëÄã×Ô¼ºµÄ?__builtins__ ?×ÖµäÀ´¿ØÖƿɹ©±»Ö´ÐдúÂë¿ÉÒÔʹÓÃÄÄЩÄÚÖÃÄ£¿é¡£ Èç¹û?locals?×ֵ䱻ʡÂÔÔòËüĬÈÏΪ?globals?×ֵ䡣 Èç¹ûÁ½¸ö×ֵ䶼±»Ê¡ÂÔ,Ôò½«Ê¹Óõ÷ÓÃ?eval()?µÄ»·¾³ÖеÄ?globals?ºÍ?locals?À´Ö´Ðиñí´ïʽ¡£ ×¢Òâ,eval()?ÎÞ·¨·ÃÎʱհü»·¾³ÖеÄ?ǶÌ××÷ÓÃÓò?(·Ç¾Ö²¿±äÁ¿)¡£
·µ»ØÖµ¾ÍÊDZí´ïʽµÄÇóÖµ½á¹û¡£ Óï·¨´íÎó½«×÷ΪÒì³£±»±¨¸æ¡£ ÀýÈç:
>>>
>>> x = 1
>>> eval('x+1')
2
¸Ãº¯Êý»¹¿ÉÓÃÓÚÖ´ÐÐÈÎÒâ´úÂë¶ÔÏó(±ÈÈçÓÉ?compile()?´´½¨µÄ¶ÔÏó)¡£ Õâʱ´«ÈëµÄÊÇ´úÂë¶ÔÏó,¶ø·ÇÒ»¸ö×Ö·û´®ÁË¡£Èç¹û´úÂë¶ÔÏóÒÑÓòÎÊýΪ?mode?µÄ?'exec' ?½øÐÐÁ˱àÒë,ÄÇô?eval()?µÄ·µ»ØÖµ½«Îª?None ¡£
Ìáʾ:?exec()?º¯ÊýÖ§³ÖÓï¾äµÄ¶¯Ì¬Ö´ÐС£?globals()?ºÍ?locals()?º¯Êý·Ö±ð·µ»Øµ±Ç°µÄÈ«¾ÖºÍ±¾µØ×Öµä,¿É¹©´«¸ø?eval()?»ò?exec()?ʹÓá£
Èç¹û¸ø³öµÄÔ´Êý¾ÝÊǸö×Ö·û´®,ÄÇôÆäÇ°ºóµÄ¿Õ¸ñºÍÖƱí·û½«±»ÌÞ³ý¡£
ÁíÍâ¿ÉÒÔ²ÎÔÄ?ast.literal_eval(),¸Ãº¯Êý¿ÉÒÔ°²È«Ö´Ðнö°üº¬ÎÄ×ֵıí´ïʽ×Ö·û´®¡£
Òý·¢Ò»¸ö?Éó¼Æʼþ?exec ?¸½´ø²ÎÊý?code_object ¡£
exec(object,?[globals,?[locals,?]]*,?closure=None)
Õâ¸öº¯ÊýÖ§³Ö¶¯Ì¬Ö´ÐÐ Python ´úÂë¡£?object?±ØÐëÊÇ×Ö·û´®»òÕß´úÂë¶ÔÏó¡£ Èç¹ûÊÇ×Ö·û´®,ÄÇô¸Ã×Ö·û´®½«±»½âÎöΪһϵÁÐ Python Óï¾ä²¢Ö´ÐÐ(³ý·Ç·¢ÉúÓï·¨´íÎó)¡£?1?Èç¹ûÊÇ´úÂë¶ÔÏó,Ëü½«±»Ö±½ÓÖ´ÐС£ ÔÚÈκÎÇé¿öÏÂ,±»Ö´ÐеĴúÂ붼Ӧµ±ÊÇÓÐЧµÄÎļþÊäÈë(¼û²Î¿¼ÊÖ²áÖеÄ?ÎļþÊäÈë?Ò»½Ú)¡£ Çë×¢Ò⼴ʹÔÚ´«µÝ¸ø?exec()?º¯ÊýµÄ´úÂëµÄÉÏÏÂÎÄÖÐ,nonlocal,?yield?ºÍ?return?Óï¾äÒ²²»ÄÜÔÚº¯Êý¶¨ÒåÒÔÍâʹÓᣠ¸Ãº¯ÊýµÄ·µ»ØÖµÊÇ?None ¡£
ÎÞÂÛÔÚʲôÇé¿öÏÂ,Èç¹ûÊ¡ÂÔÁË¿ÉÑ¡²¿·Ö,´úÂ뽫ÔËÐÐÓÚµ±Ç°×÷ÓÃÓòÖС£Èç¹ûÖ»ÌṩÁË?globals,Ôò±ØÐëΪ×Öµä¶ÔÏó(¶ø²»ÄÜÊÇ×ÖµäµÄ×ÓÀà),ͬʱÓÃÓÚ´æ·ÅÈ«¾Ö±äÁ¿ºÍ¾Ö²¿±äÁ¿¡£Èç¹ûÌṩÁË?globals?ºÍ?locals,Ôò½«·Ö±ðÓÃÓÚÈ«¾Ö±äÁ¿ºÍ¾Ö²¿±äÁ¿¡£locals?¿ÉÒÔÊÇÈÎÒâ×ÖµäÓ³Éä¶ÔÏó¡£Çë¼Çס,ÔÚÄ£¿é¼¶±ð,globals ºÍ locals ÊÇͬһ¸ö×ֵ䡣Èç¹û exec »ñµÃÁ½¸ö¶ÀÁ¢µÄ¶ÔÏó×÷Ϊ?globals?ºÍ?locals,´úÂëÖ´ÐÐÆðÀ´¾ÍÏñǶÈ뵽ij¸öÀඨÒåÖÐÒ»Ñù¡£
Èç¹û?globals?×ֵ䲻°üº¬?__builtins__ ?¼üÖµ,Ôò½«Îª¸Ã¼ü²åÈë¶ÔÄÚ½¨?builtins?Ä£¿é×ÖµäµÄÒýÓá£Òò´Ë,ÔÚ½«Ö´ÐеĴúÂë´«µÝ¸ø?exec()?֮ǰ,¿ÉÒÔͨ¹ý½«×Ô¼ºµÄ?__builtins__ ?×Öµä²åÈëµ½?globals?ÖÐÀ´¿ØÖÆ¿ÉÒÔʹÓÃÄÄЩÄÚÖôúÂë¡£
The?closure?argument specifies a closure--a tuple of cellvars. It's only valid when the?object?is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.
Òý·¢Ò»¸ö?Éó¼Æʼþ?exec ?¸½´ø²ÎÊý?code_object ¡£
±¸×¢
ÄÚÖÃ?globals()?ºÍ?locals()?º¯Êý¸÷×Ô·µ»Øµ±Ç°µÄÈ«¾ÖºÍ±¾µØ×Öµä,Òò´Ë¿ÉÒÔ½«ËüÃÇ´«µÝ¸ø?exec()?µÄµÚ¶þ¸öºÍµÚÈý¸öʵ²Î¡£
±¸×¢
ĬÈÏÇé¿öÏÂ,locals?µÄÐÐΪÈçÏÂÃæ?locals()?º¯ÊýÃèÊöµÄÒ»Ñù:²»ÒªÊÔͼ¸Ä±äĬÈϵÄ?locals?×ֵ䡣 Èç¹ûÄúÐèÒªÔÚ?exec()?º¯Êý·µ»Øʱ²é¿´´úÂë¶Ô?locals?µÄÓ°Ïì,ÇëÃ÷È·µØ´«µÝ?locals?×ֵ䡣
ÔÚ 3.11 °æ¸ü¸Ä:?Added the?closure?parameter.
filter(function,?iterable)
ÓÃ?iterable?Öк¯Êý?function?·µ»ØÕæµÄÄÇЩԪËØ,¹¹½¨Ò»¸öеĵü´úÆ÷¡£iterable?¿ÉÒÔÊÇÒ»¸öÐòÁÐ,Ò»¸öÖ§³Öµü´úµÄÈÝÆ÷,»òÒ»¸öµü´úÆ÷¡£Èç¹û?function?ÊÇ?None ?,Ôò»á¼ÙÉèËüÊÇÒ»¸öÉí·Ýº¯Êý,¼´?iterable?ÖÐËùÓзµ»Ø¼ÙµÄÔªËػᱻÒƳý¡£
Çë×¢Òâ,?filter(function,?iterable) ?Ï൱ÓÚÒ»¸öÉú³ÉÆ÷±í´ïʽ,µ± function ²»ÊÇ?None ?µÄʱºòΪ?(item?for?item?in?iterable?if?function(item)) ;function ÊÇ?None ?µÄʱºòΪ?(item?for?item?in?iterable?if?item) ?¡£
Çë²ÎÔÄ?itertools.filterfalse()?Á˽â,Ö»ÓÐ?function?·µ»Ø false ʱ²ÅÑ¡È¡?iterable?ÖÐÔªËصIJ¹³äº¯Êý¡£
class?float([x])
·µ»Ø´ÓÊý×Ö»ò×Ö·û´®?x?Éú³ÉµÄ¸¡µãÊý¡£
Èç¹û²ÎÊýÊǸö×Ö·û´®,ÔòÓ¦°üº¬Ò»¸öÊ®½øÖÆÊý×Ö,Ç°Ãæ¿ÉÑ¡´øÉÏ·ûºÅ,Ò²¿ÉÑ¡Ç°ºó´øÓпհ׷û¡£·ûºÅ¿ÉÒÔÊÇ``'+'`` »ò?'-' ;'+' ?·ûºÅ¶ÔֵûÓÐÓ°Ïì¡£²ÎÊýÒ²¿ÉÒÔÊÇÒ»¸ö´ú±í NaN(·ÇÊý×Ö)»òÕý¸ºÎÞÇî´óµÄ×Ö·û´®¡£¸üÈ·ÇеØ˵,ÔÚÈ¥³ýÇ°µ¼ºÍβ²¿µÄ¿Õ°×·ûºó,ÊäÈë²ÎÊý±ØÐë·ûºÏÒÔÏÂÓï·¨:
sign ::= "+" | "-"
infinity ::= "Infinity" | "inf"
nan ::= "nan"
numeric_value ::=
floatnumber
| infinity | nan
numeric_string ::= [sign] numeric_value
ÕâÀïµÄ?floatnumber ?ÊÇÖ¸ Python µÄ¸¡µãÊý¸ñʽ,ÔÚ?¸¡µãÊý×ÖÃæÖµ?ÖÐÓнéÉÜ¡£´óСдûÓйØϵ,ËùÒÔ¡°inf¡±¡¢¡°Inf¡±¡¢¡°INFINITY¡±¡¢¡°iNfINity¡±¶¼¿É½ÓÊÜΪÕýÎÞÇîµÄƴдÐÎʽ¡£
ÁíÒ»·½Ãæ,Èç¹ûʵ²ÎÊÇÕûÊý»ò¸¡µãÊý,Ôò·µ»Ø¾ßÓÐÏàֵͬ(ÔÚ Python ¸¡µã¾«¶È·¶Î§ÄÚ)µÄ¸¡µãÊý¡£Èç¹ûʵ²ÎÔÚ Python ¸¡µã¾«¶È·¶Î§Íâ,Ôò»á´¥·¢?OverflowError¡£
¶ÔÓÚÒ»¸öÆÕͨ Python ¶ÔÏó?x ,float(x) ?»áίÍиø?x.__float__() ¡£ Èç¹û?__float__() ?䶨ÒåÔò½«»ØÍËÖÁ?__index__() ¡£
Èç¹ûûÓÐʵ²Î,Ôò·µ»Ø?0.0 ?¡£
ʾÀý:
>>>
>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
Êý×ÖÀàÐÍ --- int, float, complex?ÃèÊöÁ˸¡µãÀàÐÍ¡£
ÔÚ 3.6 °æ¸ü¸Ä:?Äú¿ÉÒÔʹÓÃÏ»®Ïß½«´úÂëÎÄ×ÖÖеÄÊý×Ö½øÐзÖ×é¡£
ÔÚ 3.7 °æ¸ü¸Ä:?x?ÏÖÔÚÖ»ÄÜ×÷ΪλÖòÎÊý¡£
ÔÚ 3.8 °æ¸ü¸Ä:?Èç¹û?__float__() ?䶨ÒåÔò»ØÍËÖÁ?__index__() ¡£
format(value[,?format_spec])
½«?value?ת»»Îª¡°¸ñʽ»¯ºó¡±µÄÐÎʽ,¸ñʽÓÉ?format_spec?½øÐпØÖÆ¡£format_spec?µÄ½âÊÍ·½Ê½È¡¾öÓÚ?value?²ÎÊýµÄÀàÐÍ;µ«´ó¶àÊýÄÚÖÃÀàÐÍʹÓÃÒ»ÖÖ±ê×¼µÄ¸ñʽ»¯Óï·¨:?¸ñʽ¹æ¸ñÃÔÄãÓïÑÔ¡£
ĬÈϵÄ?format_spec?ÊÇÒ»¸ö¿Õ×Ö·û´®,Ëüͨ³£¸ø³öÓëµ÷ÓÃ?str(value)?ÏàͬµÄ½á¹û¡£
µ÷ÓÃ?format(value,?format_spec) ?»áת»»³É?type(value).__format__(value,?format_spec) ?,ËùÒÔʵÀý×ÖµäÖеÄ?__format__() ?·½·¨½«²»»áµ÷Óá£Èç¹û·½·¨ËÑË÷»ØÍ˵½?object?À൫?format_spec?²»Îª¿Õ,»òÕßÈç¹û?format_spec?»ò·µ»ØÖµ²»ÊÇ×Ö·û´®,Ôò»á´¥·¢?TypeError?Òì³£¡£
ÔÚ 3.4 °æ¸ü¸Ä:?µ±?format_spec?²»ÊÇ¿Õ×Ö·û´®Ê±,?object().__format__(format_spec) ?»á´¥·¢?TypeError¡£
class?frozenset([iterable])
·µ»ØÒ»¸öеÄ?frozenset?¶ÔÏó,Ëü°üº¬¿ÉÑ¡²ÎÊý?iterable?ÖеÄÔªËØ¡£?frozenset ?ÊÇÒ»¸öÄÚÖõÄÀà¡£ÓйشËÀàµÄÎĵµ,Çë²ÎÔÄ?frozenset?ºÍ?¼¯ºÏÀàÐÍ --- set, frozenset¡£
Çë²ÎÔÄÄÚ½¨µÄ?set¡¢list¡¢tuple?ºÍ?dict?Àà,ÒÔ¼°?collections?Ä£¿éÀ´Á˽âÆäËüµÄÈÝÆ÷¡£
getattr(object,?name[,?default])
·µ»Ø¶ÔÏóÃüÃûÊôÐÔµÄÖµ¡£name?±ØÐëÊÇ×Ö·û´®¡£Èç¹û¸Ã×Ö·û´®ÊǶÔÏóµÄÊôÐÔÖ®Ò»,Ôò·µ»Ø¸ÃÊôÐÔµÄÖµ¡£ÀýÈç,?getattr(x,?'foobar') ?µÈͬÓÚ?x.foobar ¡£Èç¹ûÖ¸¶¨µÄÊôÐÔ²»´æÔÚ,ÇÒÌṩÁË?default?Öµ,Ôò·µ»ØËü,·ñÔò´¥·¢?AttributeError¡£
±¸×¢
ÓÉÓÚ?˽ÓÐÃû³Æ»ìºÏ?·¢ÉúÔÚ±àÒëʱ,Òò´Ë±ØÐë ÊÖ¶¯»ìºÏ˽ÓÐÊôÐÔ(ÒÔÁ½¸öÏ»®Ïß´òÍ·µÄÊôÐÔ)Ãû³ÆÒÔʹʹÓÃ?getattr()?À´ÌáÈ¡Ëü¡£
globals()
·µ»ØʵÏÖµ±Ç°Ä£¿éÃüÃû¿Õ¼äµÄ×ֵ䡣¶ÔÓÚº¯ÊýÄڵĴúÂë,ÕâÊÇÔÚ¶¨Ò庯ÊýʱÉèÖõÄ,ÎÞÂÛº¯ÊýÔÚÄÄÀï±»µ÷Óö¼±£³Ö²»±ä¡£
hasattr(object,?name)
¸Ãʵ²ÎÊÇÒ»¸ö¶ÔÏóºÍÒ»¸ö×Ö·û´®¡£Èç¹û×Ö·û´®ÊǶÔÏóµÄÊôÐÔÖ®Ò»µÄÃû³Æ,Ôò·µ»Ø?True ,·ñÔò·µ»Ø?False ¡£(´Ë¹¦ÄÜÊÇͨ¹ýµ÷ÓÃ?getattr(object,?name) ?¿´ÊÇ·ñÓÐ?AttributeError?Òì³£À´ÊµÏֵġ£)
hash(object)
·µ»Ø¸Ã¶ÔÏóµÄ¹þÏ£Öµ(Èç¹ûËüÓеĻ°)¡£¹þÏ£ÖµÊÇÕûÊý¡£ËüÃÇÔÚ×Öµä²éÕÒÔªËØʱÓÃÀ´¿ìËٱȽÏ×ÖµäµÄ¼ü¡£Ïàͬ´óСµÄÊý×Ö±äÁ¿ÓÐÏàͬµÄ¹þÏ£Öµ(¼´Ê¹ËüÃÇÀàÐͲ»Í¬,Èç 1 ºÍ 1.0)¡£
±¸×¢
Èç¹û¶ÔÏóʵÏÖÁË×Ô¼ºµÄ?__hash__() ?·½·¨,Çë×¢Òâ,hash()?¸ù¾Ý»úÆ÷µÄ×Ö³¤À´½Ø¶Ï·µ»ØÖµ¡£ÁíÇë²ÎÔÄ?__hash__() ¡£
help([object])
Æô¶¯ÄÚÖõİïÖúϵͳ(´Ëº¯ÊýÖ÷ÒªÔÚ½»»¥Ê½ÖÐʹÓÃ)¡£Èç¹ûûÓÐʵ²Î,½âÊÍÆ÷¿ØÖÆ̨Àï»áÆô¶¯½»»¥Ê½°ïÖúϵͳ¡£Èç¹ûʵ²ÎÊÇÒ»¸ö×Ö·û´®,ÔòÔÚÄ£¿é¡¢º¯Êý¡¢Àà¡¢·½·¨¡¢¹Ø¼ü×Ö»òÎĵµÖ÷ÌâÖÐËÑË÷¸Ã×Ö·û´®,²¢ÔÚ¿ØÖÆ̨ÉÏ´òÓ¡°ïÖúÐÅÏ¢¡£Èç¹ûʵ²ÎÊÇÆäËûÈÎÒâ¶ÔÏó,Ôò»áÉú³É¸Ã¶ÔÏóµÄ°ïÖúÒ³¡£
Çë×¢Òâ,Èç¹ûÔÚµ÷ÓÃ?help()?ʱ,Ä¿±êº¯ÊýµÄÐβÎÁбíÖдæÔÚб¸Ü(/),ÔòÒâζ×Åб¸Ü֮ǰµÄ²ÎÊýÖ»ÄÜÊÇλÖòÎÊý¡£ÏêÇéÇë²ÎÔÄ?ÓйؽöÏÞλÖÃÐÎ²ÎµÄ FAQ ÌõÄ¿¡£
¸Ãº¯Êýͨ¹ý?site?Ä£¿é¼ÓÈëµ½ÄÚÖÃÃüÃû¿Õ¼ä¡£
ÔÚ 3.4 °æ¸ü¸Ä:?pydoc?ºÍ?inspect?µÄ±ä¸üʹµÃ¿Éµ÷ÓöÔÏóµÄÇ©ÃûÐÅÏ¢¸ü¼ÓÈ«ÃæºÍÒ»Ö¡£
hex(x)
½«ÕûÊýת»»ÎªÒÔ¡°0x¡±ÎªÇ°×ºµÄСдʮÁù½øÖÆ×Ö·û´®¡£Èç¹û?x?²»ÊÇ Python?int?¶ÔÏó,Ôò±ØÐ붨Òå·µ»ØÕûÊýµÄ?__index__() ?·½·¨¡£Ò»Ð©Àý×Ó:
>>>
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
Èç¹ûÒª½«ÕûÊýת»»Îª´óд»òСдµÄÊ®Áù½øÖÆ×Ö·û´®,²¢¿ÉÑ¡ÔñÓÐÎÞ¡°0x¡±Ç°×º,Ôò¿ÉÒÔʹÓÃÈçÏ·½·¨:
>>>
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')
Áí¼û?format()?»ñÈ¡¸ü¶àÐÅÏ¢¡£
ÁíÇë²ÎÔÄ?int()?½«Ê®Áù½øÖÆ×Ö·û´®×ª»»ÎªÒÔ 16 Ϊ»ùÊýµÄÕûÊý¡£
±¸×¢
Èç¹ûÒª»ñÈ¡¸¡µãÊýµÄÊ®Áù½øÖÆ×Ö·û´®ÐÎʽ,ÇëʹÓÃ?float.hex()?·½·¨¡£
id(object)
·µ»Ø¶ÔÏóµÄ¡°±êʶֵ¡±¡£¸ÃÖµÊÇÒ»¸öÕûÊý,Ôڴ˶ÔÏóµÄÉúÃüÖÜÆÚÖб£Ö¤ÊÇΨһÇҺ㶨µÄ¡£Á½¸öÉúÃüÆÚ²»ÖصþµÄ¶ÔÏó¿ÉÄܾßÓÐÏàͬµÄ?id()?Öµ¡£
CPython implementation detail:?This is the address of the object in memory.
Òý·¢Ò»¸ö?Éó¼Æʼþ?builtins.id ,¸½´ø²ÎÊý?id ¡£
input([prompt])
Èç¹û´æÔÚ?prompt?ʵ²Î,Ôò½«ÆäдÈë±ê×¼Êä³ö,ĩβ²»´ø»»Ðзû¡£½ÓÏÂÀ´,¸Ãº¯Êý´ÓÊäÈëÖжÁÈ¡Ò»ÐÐ,½«Æäת»»Îª×Ö·û´®(³ýÁËĩβµÄ»»Ðзû)²¢·µ»Ø¡£µ±¶ÁÈ¡µ½ EOF ʱ,Ôò´¥·¢?EOFError¡£ÀýÈç:
>>>
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
Èç¹û¼ÓÔØÁË?readline?Ä£¿é,input()?½«Ê¹ÓÃËüÀ´Ìṩ¸´ÔÓµÄÐб༺ÍÀúÊ·¼Ç¼¹¦ÄÜ¡£
Òý·¢Ò»¸ö?Éó¼Æʼþ?builtins.input ?¸½´ø²ÎÊý?prompt ¡£
Ôڳɹ¦¶ÁÈ¡ÊäÈëÖ®ºóÒý·¢Ò»¸ö?Éó¼Æʼþ?builtins.input/result ?¸½´ø½á¹û¡£
class?int([x])
class?int(x,?base=10)
·µ»ØÒ»¸ö»ùÓÚÊý×Ö»ò×Ö·û´®?x?¹¹ÔìµÄÕûÊý¶ÔÏó,»òÕßÔÚδ¸ø³ö²ÎÊýʱ·µ»Ø?0 ¡£ Èç¹û?x?¶¨ÒåÁË?__int__() ,int(x) ?½«·µ»Ø?x.__int__() ¡£ Èç¹û?x?¶¨ÒåÁË?__index__() ,Ëü½«·µ»Ø?x.__index__() ¡£ Èç¹û?x?¶¨ÒåÁË?__trunc__() ,Ëü½«·µ»Ø?x.__trunc__() ¡£ ¶ÔÓÚ¸¡µãÊý,Ëü½«ÏòÁãÉáÈë¡£
Èç¹û?x?²»ÊÇÊý×Ö,»òÕßÓÐ?base?²ÎÊý,x?±ØÐëÊÇ×Ö·û´®¡¢bytes¡¢±íʾ½øÖÆΪ?base?µÄ?ÕûÊý×ÖÃæÖµ?µÄ?bytearray?ʵÀý¡£¸ÃÎÄ×ÖÇ°¿ÉÒÔÓÐ?+ ?»ò?- ?(Öм䲻ÄÜÓпոñ),Ç°ºó¿ÉÒÔÓпոñ¡£Ò»¸ö½øÖÆΪ n µÄÊý×Ö°üº¬ 0 µ½ n-1 µÄÊý,ÆäÖÐ?a ?µ½?z ?(»ò?A ?µ½?Z ?)±íʾ 10 µ½ 35¡£Ä¬ÈϵÄ?base?Ϊ 10 ,ÔÊÐíµÄ½øÖÆÓÐ 0¡¢2-36¡£2¡¢8¡¢16 ½øÖƵÄÊý×Ö¿ÉÒÔÔÚ´úÂëÖÐÓÃ?0b /0B ?¡¢?0o /0O ?¡¢?0x /0X ?ǰ׺À´±íʾ¡£½øÖÆΪ 0 ½«°²ÕÕ´úÂëµÄ×ÖÃæÁ¿À´¾«È·½âÊÍ,×îºóµÄ½á¹û»áÊÇ 2¡¢8¡¢10¡¢16 ½øÖÆÖеÄÒ»¸ö¡£ËùÒÔ?int('010',?0) ?ÊÇ·Ç·¨µÄ,µ«?int('010') ?ºÍ?int('010',?8) ?ÊǺϷ¨µÄ¡£
ÕûÊýÀàÐͶ¨ÒåÇë²ÎÔÄ?Êý×ÖÀàÐÍ --- int, float, complex?¡£
ÔÚ 3.4 °æ¸ü¸Ä:?Èç¹û?base?²»ÊÇ?int?µÄʵÀý,µ«?base?¶ÔÏóÓÐ?base.__index__?·½·¨,Ôò»áµ÷Óø÷½·¨À´»ñÈ¡½øÖÆÊý¡£ÒÔÇ°µÄ°æ±¾Ê¹ÓÃ?base.__int__?¶ø²»ÊÇ?base.__index__¡£
ÔÚ 3.6 °æ¸ü¸Ä:?Äú¿ÉÒÔʹÓÃÏ»®Ïß½«´úÂëÎÄ×ÖÖеÄÊý×Ö½øÐзÖ×é¡£
ÔÚ 3.7 °æ¸ü¸Ä:?x?ÏÖÔÚÖ»ÄÜ×÷ΪλÖòÎÊý¡£
ÔÚ 3.8 °æ¸ü¸Ä:?Èç¹û?__int__() ?䶨ÒåÔò»ØÍËÖÁ?__index__() ¡£
ÔÚ 3.11 °æ¸ü¸Ä:?The delegation to?__trunc__() ?is deprecated.
isinstance(object,?classinfo)
Return?True ?if the?object?argument is an instance of the?classinfo?argument, or of a (direct, indirect, or?virtual) subclass thereof. If?object?is not an object of the given type, the function always returns?False . If?classinfo?is a tuple of type objects (or recursively, other such tuples) or a?union ÀàÐÍ?of multiple types, return?True ?if?object?is an instance of any of the types. If?classinfo?is not a type or tuple of types and such tuples, a?TypeError?exception is raised.?TypeError?may not be raised for an invalid type if an earlier check succeeds.
ÔÚ 3.10 °æ¸ü¸Ä:?classinfo?¿ÉÒÔÊÇÒ»¸ö?union ÀàÐÍ¡£
issubclass(class,?classinfo)
Èç¹û?class?ÊÇ?classinfo?µÄ×ÓÀà(Ö±½Ó¡¢¼ä½Ó»ò?ÐéµÄ?),Ôò·µ»Ø?True ¡£ÀཫÊÓΪ×Ô¼ºµÄ×ÓÀà¡£classinfo?¿ÉΪÀà¶ÔÏóµÄÔª×é(»òµÝ¹éµØ,ÆäËûÕâÑùµÄÔª×é)»ò?union ÀàÐÍ,ÕâʱÈç¹û?class?ÊÇ?classinfo?ÖÐÈκÎÌõÄ¿µÄ×ÓÀà,Ôò·µ»Ø?True ?¡£ÈκÎÆäËûÇé¿ö¶¼»á´¥·¢?TypeError?Òì³£¡£
ÔÚ 3.10 °æ¸ü¸Ä:?classinfo?¿ÉÒÔÊÇÒ»¸ö?union ÀàÐÍ¡£
iter(object[,?sentinel])
·µ»ØÒ»¸ö?iterator?¶ÔÏ󡣸ù¾ÝÊÇ·ñ´æÔÚµÚ¶þ¸öʵ²Î,µÚÒ»¸öʵ²ÎµÄ½âÊÍÊǷdz£²»Í¬µÄ¡£Èç¹ûûÓеڶþ¸öʵ²Î,object?±ØÐëÊÇÖ§³Ö?iterable?ÐÒé(ÓÐ?__iter__() ?·½·¨)µÄ¼¯ºÏ¶ÔÏó,»ò±ØÐëÖ§³ÖÐòÁÐÐÒé(ÓÐ?__getitem__() ?·½·¨,ÇÒÊý×Ö²ÎÊý´Ó?0 ?¿ªÊ¼)¡£Èç¹ûËü²»Ö§³ÖÕâЩÐÒé,»á´¥·¢?TypeError¡£Èç¹ûÓеڶþ¸öʵ²Î?sentinel,ÄÇô?object?±ØÐëÊǿɵ÷ÓõĶÔÏó¡£ÕâÖÖÇé¿öÏÂÉú³ÉµÄµü´úÆ÷,ÿ´Îµü´úµ÷ÓÃËüµÄ?__next__()?·½·¨Ê±¶¼»á²»´øʵ²ÎµØµ÷ÓÃ?object;Èç¹û·µ»ØµÄ½á¹ûÊÇ?sentinel?Ôò´¥·¢?StopIteration,·ñÔò·µ»Øµ÷Óýá¹û¡£
ÁíÇë²ÎÔÄ?µü´úÆ÷ÀàÐÍ¡£
ÊʺÏ?iter()?µÄµÚ¶þÖÖÐÎʽµÄÓ¦ÓÃÖ®Ò»Êǹ¹½¨¿é¶ÁÈ¡Æ÷¡£ ÀýÈç,´Ó¶þ½øÖÆÊý¾Ý¿âÎļþÖжÁÈ¡¹Ì¶¨¿í¶ÈµÄ¿é,Ö±ÖÁµ½´ïÎļþµÄĩβ:
from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), b''):
process_block(block)
len(s)
·µ»Ø¶ÔÏóµÄ³¤¶È(ÔªËظöÊý)¡£Êµ²Î¿ÉÒÔÊÇÐòÁÐ(Èç string¡¢bytes¡¢tuple¡¢list »ò range µÈ)»ò¼¯ºÏ(Èç dictionary¡¢set »ò frozen set µÈ)¡£
CPython implementation detail:?len ?¶ÔÓÚ´óÓÚ?sys.maxsize?µÄ³¤¶ÈÈç?range(2?**?100)?»áÒý·¢?OverflowError¡£
class?list([iterable])
ËäÈ»±»³ÆΪº¯Êý,list?ʵ¼ÊÉÏÊÇÒ»ÖֿɱäÐòÁÐÀàÐÍ,ÏêÇéÇë²ÎÔÄ?Áбí?ºÍ?ÐòÁÐÀàÐÍ --- list, tuple, range¡£
locals()
¸üв¢·µ»Ø±íʾµ±Ç°±¾µØ·ûºÅ±íµÄ×ֵ䡣 ÔÚº¯Êý´úÂë¿éµ«²»ÊÇÀà´úÂë¿éÖе÷ÓÃ?locals()?ʱ½«·µ»Ø×ÔÓɱäÁ¿¡£ Çë×¢ÒâÔÚÄ£¿é²ã¼¶ÉÏ,locals()?ºÍ?globals()?ÊÇͬһ¸ö×ֵ䡣
±¸×¢
²»Òª¸ü¸Ä´Ë×ÖµäµÄÄÚÈÝ;¸ü¸Ä²»»áÓ°Ïì½âÊÍÆ÷ʹÓõľֲ¿±äÁ¿»ò×ÔÓɱäÁ¿µÄÖµ¡£
map(function,?iterable,?...)
·µ»ØÒ»¸ö½«?function?Ó¦ÓÃÓÚ?iterable?ÖÐÿһÏî²¢Êä³öÆä½á¹ûµÄµü´úÆ÷¡£ Èç¹û´«ÈëÁ˶îÍâµÄ?iterable?²ÎÊý,function?±ØÐë½ÓÊÜÏàͬ¸öÊýµÄʵ²Î²¢±»Ó¦ÓÃÓÚ´ÓËùÓпɵü´ú¶ÔÏóÖв¢ÐлñÈ¡µÄÏî¡£ µ±Óжà¸ö¿Éµü´ú¶ÔÏóʱ,×î¶ÌµÄ¿Éµü´ú¶ÔÏóºÄ¾¡ÔòÕû¸öµü´ú¾Í½«½áÊø¡£ ¶ÔÓÚº¯ÊýµÄÊäÈëÒѾÊDzÎÊýÔª×éµÄÇé¿ö,Çë²ÎÔÄ?itertools.starmap()¡£
max(iterable,?*[,?key,?default])
max(arg1,?arg2,?*args[,?key])
·µ»Ø¿Éµü´ú¶ÔÏóÖÐ×î´óµÄÔªËØ,»òÕß·µ»ØÁ½¸ö¼°ÒÔÉÏʵ²ÎÖÐ×î´óµÄ¡£
Èç¹ûÖ»ÌṩÁËÒ»¸öλÖòÎÊý,Ëü±ØÐëÊÇ·Ç¿Õ?iterable,·µ»Ø¿Éµü´ú¶ÔÏóÖÐ×î´óµÄÔªËØ;Èç¹ûÌṩÁËÁ½¸ö¼°ÒÔÉϵÄλÖòÎÊý,Ôò·µ»Ø×î´óµÄλÖòÎÊý¡£
ÓÐÁ½¸ö¿ÉÑ¡Ö»ÄÜÓùؼü×ÖµÄʵ²Î¡£key?ʵ²ÎÖ¸¶¨ÅÅÐòº¯ÊýÓõIJÎÊý,Èç´«¸ø?list.sort()?µÄ¡£default?ʵ²ÎÊǵ±¿Éµü´ú¶ÔÏóΪ¿Õʱ·µ»ØµÄÖµ¡£Èç¹û¿Éµü´ú¶ÔÏóΪ¿Õ,²¢ÇÒûÓиø?default?,Ôò»á´¥·¢?ValueError¡£
Èç¹ûÓжà¸ö×î´óÔªËØ,Ôò´Ëº¯Êý½«·µ»ØµÚÒ»¸öÕÒµ½µÄ¡£ÕâºÍÆäËûÎȶ¨ÅÅÐò¹¤¾ßÈç?sorted(iterable,?key=keyfunc,?reverse=True)[0] ?ºÍ?heapq.nlargest(1,?iterable,?key=keyfunc) ?±£³ÖÒ»Ö¡£
3.4 а湦ÄÜ:?keyword-only ʵ²Î?default?¡£
ÔÚ 3.8 °æ¸ü¸Ä:?key?¿ÉÒÔΪ?None ¡£
class?memoryview(object)
·µ»ØÓɸø¶¨Êµ²Î´´½¨µÄ¡°ÄÚ´æÊÓͼ¡±¶ÔÏó¡£ÓйØÏêϸÐÅÏ¢,Çë²ÎÔÄ?ÄÚ´æÊÓͼ¡£
min(iterable,?*[,?key,?default])
min(arg1,?arg2,?*args[,?key])
·µ»Ø¿Éµü´ú¶ÔÏóÖÐ×îСµÄÔªËØ,»òÕß·µ»ØÁ½¸ö¼°ÒÔÉÏʵ²ÎÖÐ×îСµÄ¡£
Èç¹ûÖ»ÌṩÁËÒ»¸öλÖòÎÊý,Ëü±ØÐëÊÇ?iterable,·µ»Ø¿Éµü´ú¶ÔÏóÖÐ×îСµÄÔªËØ;Èç¹ûÌṩÁËÁ½¸ö¼°ÒÔÉϵÄλÖòÎÊý,Ôò·µ»Ø×îСµÄλÖòÎÊý¡£
ÓÐÁ½¸ö¿ÉÑ¡Ö»ÄÜÓùؼü×ÖµÄʵ²Î¡£key?ʵ²ÎÖ¸¶¨ÅÅÐòº¯ÊýÓõIJÎÊý,Èç´«¸ø?list.sort()?µÄ¡£default?ʵ²ÎÊǵ±¿Éµü´ú¶ÔÏóΪ¿Õʱ·µ»ØµÄÖµ¡£Èç¹û¿Éµü´ú¶ÔÏóΪ¿Õ,²¢ÇÒûÓиø?default?,Ôò»á´¥·¢?ValueError¡£
Èç¹ûÓжà¸ö×îСԪËØ,Ôò´Ëº¯Êý½«·µ»ØµÚÒ»¸öÕÒµ½µÄ¡£ÕâºÍÆäËûÎȶ¨ÅÅÐò¹¤¾ßÈç?sorted(iterable,?key=keyfunc)[0] ?ºÍ?heapq.nsmallest(1,?iterable,?key=keyfunc) ?±£³ÖÒ»Ö¡£
3.4 а湦ÄÜ:?keyword-only ʵ²Î?default?¡£
ÔÚ 3.8 °æ¸ü¸Ä:?key?¿ÉÒÔΪ?None ¡£
next(iterator[,?default])
ͨ¹ýµ÷ÓÃ?iterator?µÄ?__next__()?·½·¨»ñÈ¡ÏÂÒ»¸öÔªËØ¡£Èç¹ûµü´úÆ÷ºÄ¾¡,Ôò·µ»Ø¸ø¶¨µÄ?default,Èç¹ûûÓÐĬÈÏÖµÔò´¥·¢?StopIteration¡£
class?object
·µ»ØÒ»¸ö²»´øÌØÕ÷µÄжÔÏó¡£object?ÊÇËùÓÐÀàµÄ»ùÀà¡£Ëü´øÓÐËùÓÐ Python ÀàʵÀý¾ùͨÓõķ½·¨¡£±¾º¯Êý²»½ÓÊÜÈκβÎÊý¡£
±¸×¢
ÓÉÓÚ?object?ûÓÐ?__dict__,Òò´ËÎÞ·¨½«ÈÎÒâÊôÐÔ¸³¸ø?object?µÄʵÀý¡£
oct(x)
½«Ò»¸öÕûÊýת±äΪһ¸öǰ׺Ϊ¡°0o¡±µÄ°Ë½øÖÆ×Ö·û´®¡£½á¹ûÊÇÒ»¸öºÏ·¨µÄ Python ±í´ïʽ¡£Èç¹û?x?²»ÊÇ Python µÄ?int?¶ÔÏó,ÄÇËüÐèÒª¶¨Òå?__index__() ?·½·¨·µ»ØÒ»¸öÕûÊý¡£Ò»Ð©Àý×Ó:
>>>
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
ÈôÒª½«ÕûÊýת»»Îª°Ë½øÖÆ×Ö·û´®,²¢¿ÉÑ¡ÔñÊÇ·ñ´øÓС°0o¡±Ç°×º,¿É²ÉÓÃÈçÏ·½·¨:
>>>
>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')
Áí¼û?format()?»ñÈ¡¸ü¶àÐÅÏ¢¡£
open(file,?mode='r',?buffering=-?1,?encoding=None,?errors=None,?newline=None,?closefd=True,?opener=None)
´ò¿ª?file?²¢·µ»Ø¶ÔÓ¦µÄ?file object¡£ Èç¹û¸ÃÎļþ²»Äܱ»´ò¿ª,ÔòÒý·¢?OSError¡£ Çë²ÎÔÄ?¶ÁдÎļþ?»ñÈ¡´Ëº¯ÊýµÄ¸ü¶àÓ÷¨Ê¾Àý¡£
file?ÊÇÒ»¸ö?path-like object,±íʾ½«Òª´ò¿ªµÄÎļþµÄ·¾¶(¾ø¶Ô·¾¶»òÕßÏà¶Ôµ±Ç°¹¤×÷Ŀ¼µÄ·¾¶),Ò²¿ÉÒÔÊÇÒª·â×°Îļþ¶ÔÓ¦µÄÕûÊýÀàÐÍÎļþÃèÊö·û¡£(Èç¹û¸ø³öµÄÊÇÎļþÃèÊö·û,Ôòµ±·µ»ØµÄ I/O ¶ÔÏó¹Ø±ÕʱËüÒ²»á¹Ø±Õ,³ý·Ç½«?closefd?ÉèΪ?False ?¡£)
mode?is an optional string that specifies the mode in which the file is opened. It defaults to?'r' ?which means open for reading in text mode. Other common values are?'w' ?for writing (truncating the file if it already exists),?'x' ?for exclusive creation, and?'a' ?for appending (which on?some?Unix systems, means that?all?writes append to the end of the file regardless of the current seek position). In text mode, if?encoding?is not specified the encoding used is platform-dependent:?locale.getencoding()?is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave?encoding?unspecified.) The available modes are:
×Ö·û | º¬Òâ |
---|
'r' | ¶ÁÈ¡(ĬÈÏ) | 'w' | дÈë,²¢ÏȽضÏÎļþ | 'x' | ÅÅËüÐÔ´´½¨,Èç¹ûÎļþÒÑ´æÔÚÔòʧ°Ü | 'a' | ´ò¿ªÎļþÓÃÓÚдÈë,Èç¹ûÎļþ´æÔÚÔòÔÚĩβ׷¼Ó | 'b' | ¶þ½øÖÆģʽ | 't' | Îı¾Ä£Ê½(ĬÈÏ) | '+' | ´ò¿ªÓÃÓÚ¸üÐÂ(¶ÁÈ¡ÓëдÈë) |
ĬÈÏģʽΪ?'r' ?(´ò¿ªÎļþÓÃÓÚ¶ÁÈ¡Îı¾,Óë?'rt' ?ͬÒå)¡£'w+' ?ºÍ?'w+b' ?ģʽ½«´ò¿ªÎļþ²¢Çå¿ÕÄÚÈÝ¡£¶ø?'r+' ?ºÍ?'r+b' ?ģʽ½«´ò¿ªÎļþµ«²»Çå¿ÕÄÚÈÝ¡£
ÕýÈçÔÚ?¸ÅÊö?ÖÐÌáµ½µÄ,PythonÇø·Ö¶þ½øÖƺÍÎı¾I/O¡£ÒÔ¶þ½øÖÆģʽ´ò¿ªµÄÎļþ(°üÀ¨?mode?²ÎÊýÖеÄ?'b' ?)·µ»ØµÄÄÚÈÝΪ?bytes?¶ÔÏó,²»½øÐÐÈκνâÂë¡£ÔÚÎı¾Ä£Ê½ÏÂ(ĬÈÏÇé¿öÏÂ,»òÕßÔÚ?mode?²ÎÊýÖаüº¬?'t' ?)ʱ,ÎļþÄÚÈÝ·µ»ØΪ?str?,Ê×ÏÈʹÓÃÖ¸¶¨µÄ?encoding?(Èç¹û¸ø¶¨)»òÕßʹÓÃƽ̨ĬÈϵĵÄ×Ö½Ú±àÂë½âÂë¡£
±¸×¢
Python²»ÒÀÀµÓڵײã²Ù×÷ϵͳµÄÎı¾Îļþ¸ÅÄî;ËùÓд¦Àí¶¼ÓÉPython±¾ÉíÍê³É,Òò´ËÓëƽ̨Î޹ء£
buffering?ÊÇÒ»¸ö¿ÉÑ¡µÄÕûÊý,ÓÃÓÚÉèÖûº³å²ßÂÔ¡£ ´«Èë 0 À´¹Ø±Õ»º³å(Ö»ÔÊÐíÔÚ¶þ½øÖÆģʽÏÂ),´«Èë 1 À´Ñ¡ÔñÐлº³å(Ö»ÔÚÎı¾Ä£Ê½Ï¿ÉÓÃ),´«ÈëÒ»¸öÕûÊý > 1 À´±íʾ¹Ì¶¨´óСµÄ¿é»º³åÇøµÄ×Ö½Ú´óС¡£×¢Òâ,ÕâÑùÖ¸¶¨»º³åÇøµÄ´óСÊÊÓÃÓÚ¶þ½øÖÆ»º³åµÄ I/O ,µ«?TextIOWrapper ?(¼´ÓÃ?mode='r+' ?´ò¿ªµÄÎļþ)»áÓÐÁíÒ»ÖÖ»º³å¡£Òª½ûÓÃÔÚ?TextIOWrapper ?»º³å,¿¼ÂÇʹÓÃ?io.TextIOWrapper.reconfigure()?µÄ?write_through ?±êÖ¾À´¡£µ±Ã»Óиø³ö?buffering?²ÎÊýʱ,ĬÈϵĻº³å²ßÂÔ¹¤×÷ÈçÏ¡£
-
¶þ½øÖÆÎļþÒԹ̶¨´óСµÄ¿é½øÐлº³å;ʹÓÃÆô·¢Ê½·½·¨Ñ¡Ôñ»º³åÇøµÄ´óС,³¢ÊÔÈ·¶¨µ×²ãÉ豸µÄ¡°¿é´óС¡±»òʹÓÃ?io.DEFAULT_BUFFER_SIZE¡£ÔÚÐí¶àϵͳÉÏ,»º³åÇøµÄ³¤¶Èͨ³£Îª4096»ò8192×Ö½Ú¡£ -
¡°½»»¥Ê½¡±Îı¾Îļþ(?isatty()?·µ»Ø?True ?µÄÎļþ)ʹÓÃÐлº³å¡£ÆäËûÎı¾ÎļþʹÓÃÉÏÊö²ßÂÔÓÃÓÚ¶þ½øÖÆÎļþ¡£
encoding?is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever?locale.getencoding()?returns), but any?text encoding?supported by Python can be used. See the?codecs?module for the list of supported encodings.
errors?ÊÇÒ»¸ö¿ÉÑ¡µÄ×Ö·û´®²ÎÊý,ÓÃÓÚÖ¸¶¨ÈçºÎ´¦Àí±àÂëºÍ½âÂë´íÎó - Õâ²»ÄÜÔÚ¶þ½øÖÆģʽÏÂʹÓ᣿ÉÒÔʹÓø÷ÖÖ±ê×¼´íÎó´¦Àí³ÌÐò(ÁÐÔÚ?´íÎó´¦Àí·½°¸?),µ«ÊÇʹÓÃ?codecs.register_error()?×¢²áµÄÈκδíÎó´¦ÀíÃû³ÆÒ²ÊÇÓÐЧµÄ¡£±ê×¼Ãû³Æ°üÀ¨:
-
Èç¹û´æÔÚ±àÂë´íÎó,'strict' ?»áÒý·¢?ValueError?Òì³£¡£ ĬÈÏÖµ?None ?¾ßÓÐÏàͬµÄЧ¹û¡£ -
'ignore' ?ºöÂÔ´íÎó¡£Çë×¢Òâ,ºöÂÔ±àÂë´íÎó¿ÉÄܻᵼÖÂÊý¾Ý¶ªÊ§¡£ -
'replace' ?»á½«Ìæ»»±ê¼Ç(ÀýÈç?'?' ?)²åÈëÓдíÎóÊý¾ÝµÄµØ·½¡£ -
'surrogateescape' ?½«°ÑÈκβ»ÕýÈ·µÄ×Ö½Ú±íʾΪ U+DC80 ÖÁ U+DCFF ·¶Î§ÄÚµÄÏ·½Ìæ´úÂëλ¡£ µ±ÔÚдÈëÊý¾ÝʱʹÓÃ?surrogateescape ?´íÎó´¦Àí¾ä±úʱÕâЩÌæ´úÂëλ»á±»×ª»Øµ½ÏàͬµÄ×Ö½Ú¡£ ÕâÊÊÓÃÓÚ´¦Àí¾ßÓÐδ֪±àÂë¸ñʽµÄÎļþ¡£ -
Ö»ÓÐÔÚдÈëÎļþʱ²ÅÖ§³Ö?'xmlcharrefreplace' ¡£±àÂë²»Ö§³ÖµÄ×Ö·û½«Ì滻ΪÏàÓ¦µÄXML×Ö·ûÒýÓÃ?&#nnn; ¡£ -
'backslashreplace' ?ÓÃPythonµÄ·´ÏòתÒåÐòÁÐÌæ»»¸ñʽ´íÎóµÄÊý¾Ý¡£ -
'namereplace' ?(Ò²Ö»ÔÚ±àдʱ֧³Ö)ÓÃ?\N{...} ?תÒåÐòÁÐÌæ»»²»Ö§³ÖµÄ×Ö·û¡£
newline?¿ØÖÆ?universal newlines?ģʽÈçºÎÉúЧ(Ëü½öÊÊÓÃÓÚÎı¾Ä£Ê½)¡£Ëü¿ÉÒÔÊÇ?None ,'' ,'\n' ,'\r' ?ºÍ?'\r\n' ¡£ËüµÄ¹¤×÷ÔÀí:
-
´ÓÁ÷ÖжÁÈ¡ÊäÈëʱ,Èç¹û?newline?Ϊ?None ,ÔòÆôÓÃͨÓû»ÐÐģʽ¡£ÊäÈëÖеÄÐпÉÒÔÒÔ?'\n' ,'\r' ?»ò?'\r\n' ?½áβ,ÕâЩÐб»·Òë³É?'\n' ?ÔÚ·µ»Øºô½ÐÕß֮ǰ¡£Èç¹ûËüÊÇ?'' ,ÔòÆôÓÃͨÓû»ÐÐģʽ,µ«Ðнá⽫·µ»Ø¸øµ÷ÓÃÕßδ·Òë¡£Èç¹ûËü¾ßÓÐÈκÎÆäËûºÏ·¨Öµ,ÔòÊäÈëÐнöÓɸø¶¨×Ö·û´®ÖÕÖ¹,²¢ÇÒÐнá⽫·µ»Ø¸øδµ÷Óõĵ÷ÓÃÕß¡£ -
½«Êä³öдÈëÁ÷ʱ,Èç¹û?newline?Ϊ?None ,ÔòдÈëµÄÈκÎ?'\n' ?×Ö·û¶¼½«×ª»»ÎªÏµÍ³Ä¬ÈÏÐзָô·û?os.linesep¡£Èç¹û?newline?ÊÇ?'' ?»ò?'\n' ,Ôò²»½øÐзÒë¡£Èç¹û?newline?ÊÇÈκÎÆäËûºÏ·¨Öµ,ÔòдÈëµÄÈκÎ?'\n' ?×Ö·û½«±»×ª»»Îª¸ø¶¨µÄ×Ö·û´®¡£
Èç¹û?closefd?Ϊ?False ?ÇÒ¸ø³öµÄ²»ÊÇÎļþÃû¶øÊÇÎļþÃèÊö·û,ÄÇôµ±Îļþ¹Ø±Õʱ,µ×²ãÎļþÃèÊö·û½«±£³Ö´ò¿ª×´Ì¬¡£Èç¹û¸ø³öµÄÊÇÎļþÃû,Ôò?closefd?±ØÐëΪ?True ?(ĬÈÏÖµ),·ñÔò½«´¥·¢´íÎó¡£
¿ÉÒÔͨ¹ý´«µÝ¿Éµ÷ÓõÄ?opener?À´Ê¹ÓÃ×Ô¶¨Ò忪ÆôÆ÷¡£È»ºóͨ¹ýʹÓòÎÊý(?file,flags?)µ÷ÓÃ?opener?»ñµÃÎļþ¶ÔÏóµÄ»ù´¡ÎļþÃèÊö·û¡£?opener?±ØÐë·µ»ØÒ»¸ö´ò¿ªµÄÎļþÃèÊö·û(ʹÓÃ?os.open?as?opener?ʱÓë´«µÝ?None ?µÄЧ¹ûÏàͬ)¡£
д´½¨µÄÎļþÊÇ?²»¿É¼Ì³ÐµÄ¡£
ÏÂÃæµÄʾÀýʹÓÃ?os.open()?º¯ÊýµÄ?dir_fd?µÄÐβÎ,´Ó¸ø¶¨µÄĿ¼ÖÐÓÃÏà¶Ô·¾¶´ò¿ªÎļþ:
>>>
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
... return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
... print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd) # don't leak a file descriptor
open()?º¯ÊýËù·µ»ØµÄ?file object?ÀàÐÍÈ¡¾öÓÚËùÓÃģʽ¡£ µ±Ê¹ÓÃ?open()?ÒÔÎı¾Ä£Ê½ ('w' ,?'r' ,?'wt' ,?'rt' ?µÈ) ´ò¿ªÎļþʱ,Ëü½«·µ»Ø?io.TextIOBase?(¾ßÌåΪ?io.TextIOWrapper) µÄÒ»¸ö×ÓÀà¡£ µ±Ê¹Óûº³åÒÔ¶þ½øÖÆģʽ´ò¿ªÎļþʱ,·µ»ØµÄÀàÊÇ?io.BufferedIOBase?µÄÒ»¸ö×ÓÀà¡£ ¾ßÌåµÄÀà»áÓжàÖÖ:ÔÚÖ»¶ÁµÄ¶þ½øÖÆģʽÏÂ,Ëü½«·µ»Ø?io.BufferedReader;ÔÚдÈë¶þ½øÖƺÍ×·¼Ó¶þ½øÖÆģʽÏÂ,Ëü½«·µ»Ø?io.BufferedWriter,¶øÔÚ¶Á/дģʽÏÂ,Ëü½«·µ»Ø?io.BufferedRandom¡£ µ±½ûÓûº³åʱ,Ôò»á·µ»ØÔʼÁ÷,¼´?io.RawIOBase?µÄÒ»¸ö×ÓÀà?io.FileIO¡£
ÁíÇë²ÎÔÄÎļþ²Ù×÷Ä£¿é,Èç?fileinput¡¢io?(ÉùÃ÷ÁË?open())¡¢os¡¢os.path¡¢tempfile?ºÍ?shutil¡£
Òý·¢Ò»¸ö?Éó¼Æʼþ?open ?¸½´ø²ÎÊý?file ,?mode ,?flags ¡£
mode ?Óë?flags ?²ÎÊý¿ÉÒÔÔÚÔʼµ÷ÓõĻù´¡Éϱ»Ð޸Ļò´«µÝ¡£
ÔÚ 3.3 °æ¸ü¸Ä:
ÔÚ 3.4 °æ¸ü¸Ä:
ÔÚ 3.5 °æ¸ü¸Ä:
ÔÚ 3.6 °æ¸ü¸Ä:
ÔÚ 3.11 °æ¸ü¸Ä:?The?'U' ?mode has been removed.
ord(c)
¶Ô±íʾµ¥¸ö Unicode ×Ö·ûµÄ×Ö·û´®,·µ»Ø´ú±íËü Unicode ÂëµãµÄÕûÊý¡£ÀýÈç?ord('a') ?·µ»ØÕûÊý?97 ,?ord('€') ?(Å·Ôª·ûºÅ)·µ»Ø?8364 ?¡£ÕâÊÇ?chr()?µÄÄ溯Êý¡£
pow(base,?exp[,?mod])
·µ»Ø?base?µÄ?exp?´ÎÃÝ;Èç¹û?mod?´æÔÚ,Ôò·µ»Ø?base?µÄ?exp?´ÎÃݶÔ?mod?È¡Óà(±È?pow(base,?exp)?%?mod ?¸ü¸ßЧ)¡£ Á½²ÎÊýÐÎʽ?pow(base,?exp) ?µÈ¼ÛÓڳ˷½ÔËËã·û:?base**exp ¡£
²ÎÊý±ØÐëΪÊýÖµÀàÐÍ¡£ ¶ÔÓÚ»ìÓõIJÙ×÷ÊýÀàÐÍ,ÔòÊÊÓöþÔªËãÊõÔËËã·ûµÄÀàÐÍÇ¿ÖÆת»»¹æÔò¡£ ¶ÔÓÚ?int?²Ù×÷Êý,½á¹û¾ßÓÐÓë²Ù×÷ÊýÏàͬµÄÀàÐÍ(ת»»ºó),³ý·ÇµÚ¶þ¸ö²ÎÊýΪ¸ºÖµ;ÔÚÕâÖÖÇé¿öÏÂ,ËùÓвÎÊý½«±»×ª»»Îª¸¡µãÊý²¢Êä³ö¸¡µãÊý½á¹û¡£ ÀýÈç,pow(10,?2) ?·µ»Ø?100 ,µ«?pow(10,?-2) ?·µ»Ø?0.01 ¡£ ¶ÔÓÚ?int?»ò?float?ÀàÐ͵ĸº»ùºÍÒ»¸ö·ÇÕûÊýµÄÖ¸Êý,»á²úÉúÒ»¸ö¸´ÔӵĽá¹û¡£ ÀýÈç,?pow(-9,?0.5) ?·µ»ØÒ»¸ö½Ó½üÓÚ?3j ?µÄÖµ¡£
¶ÔÓÚ?int?²Ù×÷Êý?base?ºÍ?exp,Èç¹û¸ø³ö?mod,Ôò?mod?±ØÐëΪÕûÊýÀàÐͲ¢ÇÒ?mod?±ØÐ벻ΪÁã¡£ Èç¹û¸ø³ö?mod?²¢ÇÒ?exp?Ϊ¸ºÖµ,Ôò?base?±ØÐëÏà¶ÔÓÚ?mod?²»¿ÉÕû³ý¡£ ÔÚÕâÖÖÇé¿öÏÂ,½«»á·µ»Ø?pow(inv_base,?-exp,?mod) ,ÆäÖÐ?inv_base?Ϊ?base?µÄµ¹Êý¶Ô?mod?È¡Óà¡£
ÏÂÃæµÄÀý×ÓÊÇ?38 ?µÄµ¹Êý¶Ô?97 ?È¡Óà:
>>>
>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True
ÔÚ 3.8 °æ¸ü¸Ä:?¶ÔÓÚ?int?²Ù×÷Êý,Èý²ÎÊýÐÎʽµÄ?pow ?ÏÖÔÚÔÊÐíµÚ¶þ¸ö²ÎÊýΪ¸ºÖµ,¼´¿ÉÒÔ¼ÆËãµ¹ÊýµÄÓàÊý¡£
ÔÚ 3.8 °æ¸ü¸Ä:?ÔÊÐí¹Ø¼ü×Ö²ÎÊý¡£ ֮ǰֻ֧³ÖλÖòÎÊý¡£
print(*objects,?sep='?',?end='\n',?file=sys.stdout,?flush=False)
½«?objects?´òÓ¡Êä³öÖÁ?file?Ö¸¶¨µÄÎı¾Á÷,ÒÔ?sep?·Ö¸ô²¢ÔÚĩβ¼ÓÉÏ?end¡£?sep?¡¢?end?¡¢?file?ºÍ?flush?±ØÐëÒԹؼü×Ö²ÎÊýµÄÐÎʽ¸ø³ö¡£
ËùÓзǹؼü×Ö²ÎÊý¶¼»á±»×ª»»Îª×Ö·û´®,¾ÍÏñÊÇÖ´ÐÐÁË?str()?Ò»Ñù,²¢»á±»Ð´Èëµ½Á÷,ÒÔ?sep?ÇÒÔÚĩβ¼ÓÉÏ?end¡£?sep?ºÍ?end?¶¼±ØÐëΪ×Ö·û´®;ËüÃÇÒ²¿ÉÒÔΪ?None ,ÕâÒâζ×ÅʹÓÃĬÈÏÖµ¡£ Èç¹ûûÓиø³ö?objects,Ôò?print()?½«Ö»Ð´Èë?end¡£
file?²ÎÊý±ØÐëÊÇÒ»¸ö¾ßÓÐ?write(string) ?·½·¨µÄ¶ÔÏó;Èç¹û²ÎÊý²»´æÔÚ»òΪ?None ,Ôò½«Ê¹ÓÃ?sys.stdout¡£ ÓÉÓÚÒª´òÓ¡µÄ²ÎÊý»á±»×ª»»ÎªÎı¾×Ö·û´®,Òò´Ë?print()?²»ÄÜÓÃÓÚ¶þ½øÖÆģʽµÄÎļþ¶ÔÏó¡£ ¶ÔÓÚÕâЩ¶ÔÏó,Ó¦¸ÄÓÃ?file.write(...) ¡£
Êä³öÊÇ·ñ»º´æͨ³£È¡¾öÓÚ?file,µ«Èç¹û?flush?¹Ø¼ü×Ö²ÎÊýΪ True,Êä³öÁ÷»á±»Ç¿ÖÆˢС£
ÔÚ 3.3 °æ¸ü¸Ä:?Ôö¼ÓÁË?flush?¹Ø¼ü×Ö²ÎÊý¡£
class?property(fget=None,?fset=None,?fdel=None,?doc=None)
·µ»Ø property ÊôÐÔ¡£
fget?ÊÇ»ñÈ¡ÊôÐÔÖµµÄº¯Êý¡£?fset?ÊÇÓÃÓÚÉèÖÃÊôÐÔÖµµÄº¯Êý¡£?fdel?ÊÇÓÃÓÚɾ³ýÊôÐÔÖµµÄº¯Êý¡£²¢ÇÒ?doc?ΪÊôÐÔ¶ÔÏó´´½¨Îĵµ×Ö·û´®¡£
Ò»¸öµäÐ͵ÄÓ÷¨ÊǶ¨ÒåÒ»¸öÍйÜÊôÐÔ?x :
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Èç¹û?c?Ϊ?C?µÄʵÀý,c.x ?½«µ÷Óà getter,c.x?=?value ?½«µ÷Óà setter,?del?c.x ?½«µ÷Óà deleter¡£
Èç¹û¸ø³ö,doc?½«³ÉΪ¸Ã property ÊôÐÔµÄÎĵµ×Ö·û´®¡£ ·ñÔò¸Ã property ½«¿½±´?fget?µÄÎĵµ×Ö·û´®(Èç¹û´æÔÚ)¡£ ÕâÁîʹÓÃ?property()?×÷Ϊ?decorator?À´´´½¨Ö»¶ÁµÄÌØÕ÷ÊôÐÔ¿ÉÒÔºÜÈÝÒ×µØʵÏÖ:
class Parrot:
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
ÒÔÉÏ?@property ?×°ÊÎÆ÷»á½«?voltage() ?·½·¨×ª»¯ÎªÒ»¸ö¾ßÓÐÏàͬÃû³ÆµÄÖ»¶ÁÊôÐ﵀ "getter",²¢½«?voltage?µÄÎĵµ×Ö·û´®ÉèÖÃΪ "Get the current voltage."
ÌØÕ÷ÊôÐÔ¶ÔÏó¾ßÓÐ?getter ,?setter ?ÒÔ¼°?deleter ?·½·¨,ËüÃÇ¿ÉÓÃ×÷×°ÊÎÆ÷À´´´½¨¸ÃÌØÕ÷ÊôÐԵĸ±±¾,²¢½«ÏàÓ¦µÄ·ÃÎʺ¯ÊýÉèΪËù×°Êεĺ¯Êý¡£ Õâ×îºÃÊÇÓÃÒ»¸öÀý×ÓÀ´½âÊÍ:
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
ÉÏÊö´úÂëÓëµÚÒ»¸öÀý×ÓÍêÈ«µÈ¼Û¡£ ×¢ÒâÒ»¶¨Òª¸ø¸½¼Óº¯ÊýÓëÔʼµÄÌØÕ÷ÊôÐÔÏàͬµÄÃû³Æ (ÔÚ±¾ÀýÖÐΪ?x ¡£)
·µ»ØµÄÌØÕ÷ÊôÐÔ¶ÔÏóͬÑù¾ßÓÐÓë¹¹ÔìÆ÷²ÎÊýÏà¶ÔÓ¦µÄÊôÐÔ?fget ,?fset ?ºÍ?fdel ¡£
ÔÚ 3.5 °æ¸ü¸Ä:?ÌØÕ÷ÊôÐÔ¶ÔÏóµÄÎĵµ×Ö·û´®ÏÖÔÚÊÇ¿ÉдµÄ¡£
class?range(stop)
class?range(start,?stop[,?step])
ËäÈ»±»³ÆΪº¯Êý,µ«?range?ʵ¼ÊÉÏÊÇÒ»¸ö²»¿É±äµÄÐòÁÐÀàÐÍ,²Î¼ûÔÚ?range ¶ÔÏó?Óë?ÐòÁÐÀàÐÍ --- list, tuple, range?ÖеÄÎĵµËµÃ÷¡£
repr(object)
·µ»Ø¶ÔÏóµÄ¿É´òÓ¡ÐÎʽ×Ö·û´®¡£¶ÔÓںܶàÀàÐͶøÑÔ,±¾º¯ÊýÊÔͼ·µ»ØµÄ×Ö·û´®,»áÓ뽫¶ÔÏ󴫸ø?eval()?ËùÉú³ÉµÄ½á¹ûÏàͬ;²»È»,½á¹û¾ÍÊÇÒ»¸ö¼âÀ¨ºÅ°ü¹üµÄ×Ö·û´®,°üº¬Á˶ÔÏóÀàÐÍÃû³Æ¼°Æ丽¼ÓÐÅÏ¢,¸½¼ÓÐÅϢͨ³£°üÀ¨¶ÔÏóµÄÃû³ÆºÍÄÚ´æµØÖ·¡£Í¨¹ý¶¨Òå?__repr__() ?·½·¨,Àà¿ÉÒÔ¿ØÖƱ¾º¯Êý½«ÎªÊµÀý·µ»ØµÄÄÚÈÝ¡£
reversed(seq)
·µ»ØÒ»¸ö·´ÏòµÄ?iterator¡£?seq?±ØÐëÊÇÒ»¸ö¾ßÓÐ?__reversed__() ?·½·¨µÄ¶ÔÏó»òÕßÊÇÖ§³Ö¸ÃÐòÁÐÐÒé(¾ßÓдÓ?0 ?¿ªÊ¼µÄÕûÊýÀàÐͲÎÊýµÄ?__len__() ?·½·¨ºÍ?__getitem__() ?·½·¨)¡£
round(number[,?ndigits])
·µ»Ø?number?ÉáÈ뵽СÊýµãºó?ndigits?λ¾«¶ÈµÄÖµ¡£ Èç¹û?ndigits?±»Ê¡ÂÔ»òΪ?None ,Ôò·µ»Ø×î½Ó½üÊäÈëÖµµÄÕûÊý¡£
¶ÔÓÚÖ§³Ö?round()?·½·¨µÄÄÚÖÃÀàÐÍ,½á¹ûÖµ»áÉáÈëÖÁ×î½Ó½üµÄ 10 µÄ¸º?ndigits?´ÎÃݵı¶Êý;Èç¹ûÓëÁ½¸ö±¶ÊýͬÑù½Ó½ü,ÔòÑ¡ÓÃżÊý¡£Òò´Ë,round(0.5) ?ºÍ?round(-0.5) ?¾ùµÃ³ö?0 ?¶ø?round(1.5) ?ÔòΪ?2 ¡£ndigits?¿ÉΪÈÎÒâÕûÊýÖµ(ÕýÊý¡¢Áã»ò¸ºÊý)¡£Èç¹ûÊ¡ÂÔÁË?ndigits?»òΪ?None ?,Ôò·µ»ØÖµ½«ÎªÕûÊý¡£·ñÔò·µ»ØÖµÓë?number?µÄÀàÐÍÏàͬ¡£
¶ÔÓÚÒ»°ãµÄ Python ¶ÔÏó?number ,?round ?½«Î¯Íиø?number.__round__ ¡£
±¸×¢
¶Ô¸¡µãÊýÖ´ÐÐ?round()?µÄÐÐΪ¿ÉÄÜ»áÁîÈ˾ªÑÈ:ÀýÈç,round(2.675,?2) ?½«¸ø³ö?2.67 ?¶ø²»ÊÇÆÚÍûµÄ?2.68 ¡£ Õâ²»ËãÊdzÌÐò´íÎó:ÕâÒ»½á¹ûÊÇÓÉÓÚ´ó¶àÊýÊ®½øÖÆСÊýʵ¼ÊÉ϶¼²»ÄÜÒÔ¸¡µãÊý¾«È·µØ±íʾ¡£ Çë²ÎÔÄ?¸¡µãËãÊõ:ÕùÒéºÍÏÞÖÆ?Á˽â¸ü¶àÐÅÏ¢¡£
class?set([iterable])
·µ»ØÒ»¸öеÄ?set?¶ÔÏó,¿ÉÒÔÑ¡Ôñ´øÓдÓ?iterable?»ñÈ¡µÄÔªËØ¡£?set ?ÊÇÒ»¸öÄÚÖÃÀàÐÍ¡£ Çë²é¿´?set?ºÍ?¼¯ºÏÀàÐÍ --- set, frozenset?»ñÈ¡¹ØÓÚÕâ¸öÀàµÄÎĵµ¡£
ÓйØÆäËûÈÝÆ÷Çë²Î¿´ÄÚÖõÄ?frozenset,?list,?tuple?ºÍ?dict?Àà,ÒÔ¼°?collections?Ä£¿é¡£
setattr(object,?name,?value)
±¾º¯ÊýÓë?getattr()?Ïà¶ÔÓ¦¡£Æä²ÎÊýΪһ¸ö¶ÔÏó¡¢Ò»¸ö×Ö·û´®ºÍÒ»¸öÈÎÒâÖµ¡£×Ö·û´®¿ÉÒÔΪijÏÖÓÐÊôÐÔµÄÃû³Æ,»òΪÐÂÊôÐÔ¡£Ö»Òª¶ÔÏóÔÊÐí,º¯Êý»á½«Öµ¸³¸øÊôÐÔ¡£Èç?setattr(x,?'foobar',?123) ?µÈ¼ÛÓÚ?x.foobar?=?123 ¡£
±¸×¢
ÓÉÓÚ?˽ÓÐÃû³Æ»ìºÏ?·¢ÉúÔÚ±àÒëʱ,Òò´Ë±ØÐëÊÖ¶¯»ìºÏ˽ÓÐÊôÐÔ(ÒÔÁ½¸öÏ»®Ïß´òÍ·µÄÊôÐÔ)Ãû³ÆÒÔ±ãʹÓÃ?setattr()?À´ÉèÖÃËü¡£
class?slice(stop)
class?slice(start,?stop[,?step])
·µ»ØÒ»¸ö?slice?¶ÔÏó,´ú±íÓÉ?range(start,?stop,?step) ?Ö¸¶¨Ë÷Òý¼¯µÄÇÐƬ¡£ ÆäÖвÎÊý?start?ºÍ?step?µÄĬÈÏֵΪ?None ¡£ÇÐƬ¶ÔÏó¾ßÓÐÖ»¶ÁÊý¾ÝÊôÐÔ?start ?¡¢stop ?ºÍ?step ,Ö»ÊÇ·µ»Ø¶ÔÓ¦µÄ²ÎÊýÖµ(»òĬÈÏÖµ)¡£Õ⼸¸öÊôÐÔûÓÐÆäËûÃ÷È·µÄ¹¦ÄÜ;²»¹ý NumPy ºÍÆäËûµÚÈý·½À©Õ¹»áÓõ½¡£ÔÚʹÓÃÀ©Õ¹Ë÷ÒýÓ﷨ʱ,Ò²»áÉú³ÉÇÐƬ¶ÔÏó¡£ÀýÈç:?a[start:stop:step] ?»ò?a[start:stop,?i] ¡£ ÁíÒ»ÖÖ·½°¸ÊÇ·µ»Øµü´úÆ÷¶ÔÏó,¿É²ÎÔÄ?itertools.islice()?¡£
sorted(iterable,?/,?*,?key=None,?reverse=False)
¸ù¾Ý?iterable?ÖеÄÏî·µ»ØÒ»¸öеÄÒÑÅÅÐòÁÐ±í¡£
¾ßÓÐÁ½¸ö¿ÉÑ¡²ÎÊý,ËüÃǶ¼±ØÐëÖ¸¶¨Îª¹Ø¼ü×Ö²ÎÊý¡£
key?Ö¸¶¨´øÓе¥¸ö²ÎÊýµÄº¯Êý,ÓÃÓÚ´Ó?iterable?µÄÿ¸öÔªËØÖÐÌáÈ¡ÓÃÓڱȽϵļü (ÀýÈç?key=str.lower )¡£ ĬÈÏֵΪ?None ?(Ö±½Ó±È½ÏÔªËØ)¡£
reverse?Ϊһ¸ö²¼¶ûÖµ¡£ Èç¹ûÉèΪ?True ,Ôòÿ¸öÁбíÔªËؽ«°´·´Ïò˳Ðò±È½Ï½øÐÐÅÅÐò¡£
ʹÓÃ?functools.cmp_to_key()?¿É½«ÀÏʽµÄ?cmp?º¯Êýת»»Îª?key?º¯Êý¡£
ÄÚÖõÄ?sorted()?È·±£ÊÇÎȶ¨µÄ¡£ Èç¹ûÒ»¸öÅÅÐòÈ·±£²»»á¸Ä±ä±È½Ï½á¹ûÏàµÈµÄÔªËصÄÏà¶Ô˳Ðò¾Í³ÆÆäΪÎȶ¨µÄ --- ÕâÓÐÀûÓÚ½øÐжàÖØÅÅÐò(ÀýÈçÏÈ°´²¿ÃÅ¡¢ÔÙ°´Ð½¼¶ÅÅÐò)¡£
ÅÅÐòË㷨ֻʹÓÃ?< ?ÔÚÏîÄ¿Ö®¼ä±È½Ï¡£ ËäÈ»¶¨ÒåÒ»¸ö?__lt__()?·½·¨¾Í×ãÒÔ½øÐÐÅÅÐò,µ«?PEP 8?½¨ÒéʵÏÖËùÓÐÁù¸ö?¸»±È½Ï?¡£ Õ⽫ÓÐÖúÓÚ±ÜÃâÔÚÓëÆäËûÅÅÐò¹¤¾ß(Èç?max()?)ʹÓÃÏàͬµÄÊý¾Ýʱ³öÏÖ´íÎó,ÕâЩ¹¤¾ßÒÀÀµÓÚ²»Í¬µÄµ×²ã·½·¨¡£ÊµÏÖËùÓÐÁù¸ö±È½ÏÒ²ÓÐÖúÓÚ±ÜÃâ»ìºÏÀàÐͱȽϵĻìÂÒ,ÒòΪ»ìºÏÀàÐͱȽϿÉÒÔµ÷Ó÷´Éäµ½?__gt__()?µÄ·½·¨¡£
ÓйØÅÅÐòʾÀýºÍ¼òÒªÅÅÐò½Ì³Ì,Çë²ÎÔÄ?ÅÅÐòÖ¸ÄÏ?¡£
@staticmethod
½«·½·¨×ª»»Îª¾²Ì¬·½·¨¡£
¾²Ì¬·½·¨²»»á½ÓÊÕÒþʽµÄµÚÒ»¸ö²ÎÊý¡£ÒªÉùÃ÷Ò»¸ö¾²Ì¬·½·¨,ÇëʹÓôËÓï·¨
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@staticmethod ?ÕâÑùµÄÐÎʽ³ÆΪº¯ÊýµÄ?decorator?-- ÏêÇé²ÎÔÄ?º¯Êý¶¨Òå¡£
¾²Ì¬·½·¨¼È¿ÉÒÔÓÉÀàÖе÷ÓÃ(Èç?C.f() ),Ò²¿ÉÒÔÓÉʵÀýÖе÷ÓÃ(Èç```C().f()``)¡£´ËÍâ,»¹¿ÉÒÔ×÷ΪÆÕͨµÄº¯Êý½øÐе÷ÓÃ(Èç``f()``)¡£
Python µÄ¾²Ì¬·½·¨Óë Java »ò C++ ÀàËÆ¡£ÁíÇë²ÎÔÄ?classmethod()?,¿ÉÓÃÓÚ´´½¨ÁíÒ»ÖÖÀ๹Ô캯Êý¡£
ÏñËùÓÐ×°ÊÎÆ÷Ò»Ñù,Ò²¿ÉÒÔÏñ³£¹æº¯ÊýÒ»Ñùµ÷ÓÃ?staticmethod ?,²¢¶ÔÆä½á¹ûÖ´ÐÐijЩ²Ù×÷¡£±ÈÈçijЩÇé¿öÏÂÐèÒª´ÓÀàÖ÷ÌåÒýÓú¯Êý²¢ÇÒÄúÏ£Íû±ÜÃâ×Ô¶¯×ª»»ÎªÊµÀý·½·¨¡£¶ÔÓÚÕâЩÇé¿ö,ÇëʹÓôËÓï·¨:
def regular_function():
...
class C:
method = staticmethod(regular_function)
ÏëÁ˽â¸ü¶àÓйؾ²Ì¬·½·¨µÄÐÅÏ¢,Çë²ÎÔÄ?±ê×¼ÀàÐͲ㼶½á¹¹?¡£
ÔÚ 3.10 °æ¸ü¸Ä:?¾²Ì¬·½·¨¼Ì³ÐÁË·½·¨µÄ¶à¸öÊôÐÔ(__module__ ¡¢__name__ ¡¢__qualname__ ¡¢__doc__ ?ºÍ?__annotations__ ),»¹ÓµÓÐÒ»¸öеÄ``__wrapped__`` ÊôÐÔ,²¢ÇÒÏÖÔÚ»¹¿ÉÒÔ×÷ΪÆÕͨº¯Êý½øÐе÷Óá£
class?str(object='')
class?str(object=b'',?encoding='utf-8',?errors='strict')
·µ»ØÒ»¸ö?str?°æ±¾µÄ?object?¡£ÓйØÏêϸÐÅÏ¢,Çë²ÎÔÄ?str()?¡£
str ?ÊÇÄÚÖÃ×Ö·û´®?class?¡£¸ü¶à¹ØÓÚ×Ö·û´®µÄÐÅÏ¢²é¿´?Îı¾ÐòÁÐÀàÐÍ --- str¡£
sum(iterable,?/,?start=0)
´Ó?start?¿ªÊ¼×Ô×óÏòÓÒ¶Ô?iterable?µÄÏîÇóºÍ²¢·µ»Ø×ܼÆÖµ¡£?iterable?µÄÏîͨ³£ÎªÊý×Ö,¶ø start ÖµÔò²»ÔÊÐíΪ×Ö·û´®¡£
¶ÔijЩÓÃÀýÀ´Ëµ,´æÔÚ?sum()?µÄ¸üºÃÌæ´ú¡£ Æ´½Ó×Ö·û´®ÐòÁеĸüºÃ¸ü¿ì·½Ê½Êǵ÷ÓÃ?''.join(sequence) ¡£ ÒªÒÔÀ©Õ¹¾«¶È¶Ô¸¡µãÖµÇóºÍ,Çë²ÎÔÄ?math.fsum()¡£ Ҫƴ½ÓһϵÁпɵü´ú¶ÔÏó,Ç뿼ÂÇʹÓÃ?itertools.chain()¡£
ÔÚ 3.8 °æ¸ü¸Ä:?start?ÐβοÉÓùؼü×Ö²ÎÊýÐÎʽÀ´Ö¸¶¨¡£
class?super([type[,?object-or-type]])
·µ»ØÒ»¸ö´úÀí¶ÔÏó,Ëü»á½«·½·¨µ÷ÓÃίÍиø?type?µÄ¸¸Àà»òÐÖµÜÀà¡£ Õâ¶ÔÓÚ·ÃÎÊÒÑÔÚÀàÖб»ÖØÔصļ̳з½·¨ºÜÓÐÓá£
object-or-type?È·¶¨ÓÃÓÚËÑË÷µÄ?method resolution order¡£ ËÑË÷»á´Ó?type?Ö®ºóµÄÀ࿪ʼ¡£
¾ÙÀýÀ´Ëµ,Èç¹û?object-or-type?µÄ?__mro__?Ϊ?D?->?B?->?C?->?A?->?object ?²¢ÇÒ?type?µÄֵΪ?B ,Ôò?super()?½«»áËÑË÷?C?->?A?->?object ¡£
object-or-type?µÄ?__mro__?ÊôÐÔÁгöÁË?getattr()?ºÍ?super()?Ëù¹²Í¬Ê¹Óõķ½·¨½âÎöËÑË÷˳Ðò¡£ ¸ÃÊôÐÔÊǶ¯Ì¬µÄ,¿ÉÒÔÔÚÈκμ̳в㼶½á¹¹·¢Éú¸üеÄʱºò±»¸Ä±ä¡£
Èç¹ûÊ¡ÂÔµÚ¶þ¸ö²ÎÊý,Ôò·µ»ØµÄ³¬Àà¶ÔÏóÊÇδ°ó¶¨µÄ¡£ Èç¹ûµÚ¶þ¸ö²ÎÊýΪһ¸ö¶ÔÏó,Ôò?isinstance(obj,?type) ?±ØÐëΪÕæÖµ¡£ Èç¹ûµÚ¶þ¸ö²ÎÊýΪһ¸öÀàÐÍ,Ôò?issubclass(type2,?type) ?±ØÐëΪÕæÖµ(ÕâÊÊÓÃÓÚÀà·½·¨)¡£
super?ÓÐÁ½¸öµäÐÍÓÃÀý¡£ ÔÚ¾ßÓе¥¼Ì³ÐµÄÀà²ã¼¶½á¹¹ÖÐ,super?¿ÉÓÃÀ´ÒýÓø¸Àà¶ø²»±ØÏÔʽµØÖ¸¶¨ËüÃǵÄÃû³Æ,´Ó¶øÁî´úÂë¸üÒ×ά»¤¡£ ÕâÖÖÓ÷¨ÓëÆäËû±à³ÌÓïÑÔÖÐ?super?µÄÓ÷¨·Ç³£ÏàËÆ¡£
µÚ¶þ¸öÓÃÀýÊÇÔÚ¶¯Ì¬Ö´Ðл·¾³ÖÐÖ§³ÖÐ×÷¶àÖؼ̳С£ ´ËÓÃÀýΪ Python Ëù¶ÀÓжø²»´æÔÚÓÚ¾²Ì¬±àÂëÓïÑÔ»ò½öÖ§³Öµ¥¼Ì³ÐµÄÓïÑÔµ±ÖС£ ÕâʹÓÃʵÏÖ¡°ÁâÐÎͼ¡±³ÉΪ¿ÉÄÜ,¼´Óжà¸ö»ùÀàʵÏÖÏàͬµÄ·½·¨¡£ ºÃµÄÉè¼ÆÇ¿ÖÆÒªÇóÕâÑùµÄ·½·¨ÔÚÿ¸öÇé¿ö϶¼¾ßÓÐÏàͬµÄµ÷ÓÃÇ©Ãû(ÒòΪµ÷ÓÃ˳ÐòÊÇÔÚÔËÐÐʱȷ¶¨µÄ,Ò²ÒòΪÕâ¸ö˳ÐòÒªÊÊÓ¦Àà²ã¼¶½á¹¹µÄ¸ü¸Ä,»¹ÒòΪÕâ¸ö˳Ðò¿ÉÄÜ°üÀ¨ÔÚÔËÐÐʱ֮ǰδ֪µÄÐÖµÜÀà)¡£
¶ÔÓÚÒÔÉÏÁ½¸öÓÃÀý,µäÐ͵ij¬Ààµ÷Óÿ´ÆðÀ´ÊÇÕâÑùµÄ:
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
³ýÁË·½·¨²éÕÒÖ®Íâ,super()?Ò²¿ÉÓÃÓÚÊôÐÔ²éÕÒ¡£ Ò»¸ö¿ÉÄܵÄÓ¦Óó¡ºÏÊÇÔÚÉϼ¶»òͬ¼¶ÀàÖе÷ÓÃ?ÃèÊöÆ÷¡£
Çë×¢Òâ?super()?ÊÇ×÷ΪÏÔʽ¼ÓµãÊôÐÔ²éÕҵİ󶨹ý³ÌµÄÒ»²¿·ÖÀ´ÊµÏÖµÄ,ÀýÈç?super().__getitem__(name) ¡£ Ëü×öµ½ÕâÒ»µãÊÇͨ¹ýʵÏÖ×Ô¼ºµÄ?__getattribute__() ?·½·¨,ÕâÑù¾ÍÄÜÒÔ¿ÉÔ¤²âµÄ˳ÐòËÑË÷Àà,²¢ÇÒÖ§³ÖÐ×÷¶àÖؼ̳С£ ¶ÔÓ¦µØ,super()?ÔÚÏñ?super()[name] ?ÕâÑùʹÓÃÓï¾ä»ò²Ù×÷·û½øÐÐÒþʽ²éÕÒʱÔòδ±»¶¨Òå¡£
»¹Òª×¢ÒâµÄÊÇ,³ýÁËÁã¸ö²ÎÊýµÄÐÎʽÒÔÍâ,super()?²¢²»ÏÞÓÚÔÚ·½·¨ÄÚ²¿Ê¹ÓᣠÁ½¸ö²ÎÊýµÄÐÎʽÃ÷È·Ö¸¶¨²ÎÊý²¢½øÐÐÏàÓ¦µÄÒýÓᣠÁã¸ö²ÎÊýµÄÐÎʽ½öÊÊÓÃÓÚÀඨÒåÄÚ²¿,ÒòΪ±àÒëÆ÷ÐèÒªÌîÈë±ØÒªµÄϸ½ÚÒÔÕýÈ·µØ¼ìË÷µ½±»¶¨ÒåµÄÀà,»¹ÐèÒªÈÃÆÕͨ·½·¨·ÃÎʵ±Ç°ÊµÀý¡£
¶ÔÓÚÓйØÈçºÎʹÓÃ?super()?À´ÈçºÎÉè¼ÆÐ×÷ÀàµÄʵÓý¨Òé,Çë²ÎÔÄ?ʹÓà super() µÄÖ¸ÄÏ¡£
class?tuple([iterable])
ËäÈ»±»³ÆΪº¯Êý,µ«?tuple?ʵ¼ÊÉÏÊÇÒ»¸ö²»¿É±äµÄÐòÁÐÀàÐÍ,²Î¼ûÔÚ?Ôª×é?Óë?ÐòÁÐÀàÐÍ --- list, tuple, range?ÖеÄÎĵµËµÃ÷¡£
class?type(object)
class?type(name,?bases,?dict,?**kwds)
´«ÈëÒ»¸ö²ÎÊýʱ,·µ»Ø?object?µÄÀàÐÍ¡£ ·µ»ØÖµÊÇÒ»¸ö type ¶ÔÏó,ͨ³£Óë?object.__class__?Ëù·µ»ØµÄ¶ÔÏóÏàͬ¡£
ÍƼöʹÓÃ?isinstance()?ÄÚÖú¯ÊýÀ´¼ì²â¶ÔÏóµÄÀàÐÍ,ÒòΪËü»á¿¼ÂÇ×ÓÀàµÄÇé¿ö¡£
´«ÈëÈý¸ö²ÎÊýʱ,·µ»ØÒ»¸öÐ嵀 type ¶ÔÏó¡£ ÕâÔÚ±¾ÖÊÉÏÊÇ?class?Óï¾äµÄÒ»ÖÖ¶¯Ì¬ÐÎʽ,name?×Ö·û´®¼´ÀàÃû²¢»á³ÉΪ?__name__?ÊôÐÔ;bases?Ôª×é°üº¬»ùÀಢ»á³ÉΪ?__bases__?ÊôÐÔ;Èç¹ûΪ¿ÕÔò»áÌí¼ÓËùÓÐÀàµÄÖÕ¼«»ùÀà?object¡£?dict?×Öµä°üº¬ÀàÖ÷ÌåµÄÊôÐԺͷ½·¨¶¨Òå;ËüÔÚ³ÉΪ?__dict__?ÊôÐÔ֮ǰ¿ÉÄܻᱻ¿½±´»ò°ü×°¡£ ÏÂÃæÁ½ÌõÓï¾ä»á´´½¨ÏàͬµÄ?type?¶ÔÏó:
>>>
>>> class X:
... a = 1
...
>>> X = type('X', (), dict(a=1))
ÁíÇë²ÎÔÄ?ÀàÐͶÔÏó¡£
Ìṩ¸øÈý²ÎÊýÐÎʽµÄ¹Ø¼ü×Ö²ÎÊý»á±»´«µÝ¸øÊʵ±µÄÔªÀà»úÖÆ (ͨ³£Îª?__init_subclass__()),Ï൱ÓÚÀඨÒåÖйؼü×Ö (³ýÁË?metaclass) µÄÐÐΪ·½Ê½¡£
ÁíÇë²ÎÔÄ?×Ô¶¨ÒåÀà´´½¨¡£
ÔÚ 3.6 °æ¸ü¸Ä:?type?µÄ×ÓÀàÈç¹ûδÖØÔØ?type.__new__ ,½«²»ÔÙÄÜʹÓÃÒ»¸ö²ÎÊýµÄÐÎʽÀ´»ñÈ¡¶ÔÏóµÄÀàÐÍ¡£
vars([object])
·µ»ØÄ£¿é¡¢ÀࡢʵÀý»òÈκÎÆäËü¾ßÓÐ?__dict__?ÊôÐԵĶÔÏóµÄ?__dict__?ÊôÐÔ¡£
Ä£¿éºÍʵÀýÕâÑùµÄ¶ÔÏó¾ßÓпɸüеÄ?__dict__?ÊôÐÔ;µ«ÊÇ,ÆäËü¶ÔÏóµÄ?__dict__?ÊôÐÔ¿ÉÄÜ»áÉèΪÏÞÖÆдÈë(ÀýÈç,Àà»áʹÓÃ?types.MappingProxyType?À´·ÀÖ¹Ö±½Ó¸üÐÂ×Öµä)¡£
²»´ø²ÎÊýʱ,vars()?µÄÐÐΪÀàËÆ?locals()¡£ Çë×¢Òâ,locals ×Öµä½ö¶ÔÓÚ¶ÁÈ¡Æð×÷ÓÃ,ÒòΪ¶Ô locals ×ÖµäµÄ¸üлᱻºöÂÔ¡£
Èç¹ûÖ¸¶¨ÁËÒ»¸ö¶ÔÏóµ«ËüûÓÐ?__dict__?ÊôÐÔ(ÀýÈç,µ±ËüËùÊôµÄÀඨÒåÁË?__slots__?ÊôÐÔʱ)Ôò»áÒý·¢?TypeError?Òì³£¡£
zip(*iterables,?strict=False)
ÔÚ¶à¸öµü´úÆ÷Éϲ¢Ðеü´ú,´Óÿ¸öµü´úÆ÷·µ»ØÒ»¸öÊý¾ÝÏî×é³ÉÔª×é¡£
ʾÀý:
>>>
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
¸üÕýʽµÄ˵·¨:?zip()?·µ»ØÔª×éµÄµü´úÆ÷,ÆäÖеÚ?i?¸öÔª×é°üº¬µÄÊÇÿ¸ö²ÎÊýµü´úÆ÷µÄµÚ?i?¸öÔªËØ¡£
²»·Á»»Ò»ÖÖ·½Ê½ÈÏʶ?zip()?:Ëü»á°ÑÐбä³ÉÁÐ,°ÑÁбä³ÉÐС£ÕâÀàËÆÓÚ?¾ØÕóתÖÃ?¡£
zip()?ÊÇÑÓ³ÙÖ´ÐеÄ:Ö±ÖÁµü´úʱ²Å»á¶ÔÔªËؽøÐд¦Àí,±ÈÈç?for ?Ñ»·»ò·ÅÈë?list?ÖС£
ÖµµÃ¿¼ÂǵÄÊÇ,´«¸ø?zip()?µÄ¿Éµü´ú¶ÔÏó¿ÉÄܳ¤¶È²»Í¬;ÓÐʱÊÇÓÐÒâΪ֮,ÓÐʱÊÇÒòΪ׼±¸ÕâЩ¶ÔÏóµÄ´úÂë´æÔÚ´íÎó¡£Python ÌṩÁËÈýÖÖ²»Í¬µÄ´¦Àí·½°¸:
-
ĬÈÏÇé¿öÏÂ,zip()?ÔÚ×î¶ÌµÄµü´úÍê³ÉºóÍ£Ö¹¡£½Ï³¤¿Éµü´ú¶ÔÏóÖеÄÊ£ÓàÏ±»ºöÂÔ,½á¹û»á²ÃÇÐÖÁ×î¶Ì¿Éµü´ú¶ÔÏóµÄ³¤¶È: >>>
>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo')] -
ͨ³£?zip()?ÓÃÓڿɵü´ú¶ÔÏóµÈ³¤µÄÇé¿öÏ¡£Õâʱ½¨ÒéÓÃ?strict=True ?µÄÑ¡Ïî¡£Êä³öÓëÆÕͨµÄ?zip()?Ïàͬ:¡£ >>>
>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
[('a', 1), ('b', 2), ('c', 3)] ÓëĬÈÏÐÐΪ²»Í¬µÄÊÇ,Ëü»á¼ì²é¿Éµü´ú¶ÔÏóµÄ³¤¶ÈÊÇ·ñÏàͬ,Èç¹û²»ÏàͬÔò´¥·¢?ValueError?¡£ >>>
>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True))
Traceback (most recent call last):
...
ValueError: zip() argument 2 is longer than argument 1 Èç¹ûδָ¶¨?strict=True ?²ÎÊý,ËùÓе¼Ö¿ɵü´ú¶ÔÏ󳤶Ȳ»Í¬µÄ´íÎ󶼻ᱻÒÖÖÆ,Õâ¿ÉÄÜ»áÔÚ³ÌÐòµÄÆäËûµØ·½±íÏÖΪÄÑÒÔ·¢ÏֵĴíÎó¡£ -
ΪÁËÈÃËùÓеĿɵü´ú¶ÔÏó¾ßÓÐÏàͬµÄ³¤¶È,³¤¶È½Ï¶ÌµÄ¿ÉÓó£Á¿½øÐÐÌî³ä¡£Õâ¿ÉÓÉ?itertools.zip_longest()?À´Íê³É¡£
¼«¶ËÀý×ÓÊÇÖ»ÓÐÒ»¸ö¿Éµü´ú¶ÔÏó²ÎÊý,zip()?»á·µ»ØÒ»¸öÒ»Ôª×éµÄµü´úÆ÷¡£Èç¹ûδ¸ø³ö²ÎÊý,Ôò·µ»ØÒ»¸ö¿ÕµÄµü´úÆ÷¡£
С¼¼ÇÉ:
-
¿ÉÈ·±£µü´úÆ÷µÄÇóֵ˳ÐòÊÇ´Ó×óµ½Óҵġ£ÕâÑù¾ÍÄÜÓÃ?zip(*[iter(s)]*n,?strict=True) ?½«Êý¾ÝÁÐ±í°´³¤¶È n ½øÐзÖ×é¡£Õ⽫Öظ´?Ïàͬ?µÄµü´úÆ÷?n ?´Î,Êä³öµÄÿ¸öÔª×鶼°üº¬?n ?´Îµ÷Óõü´úÆ÷µÄ½á¹û¡£ÕâÑù×öµÄЧ¹ûÊÇ°ÑÊäÈë²ð·ÖΪ³¤¶ÈΪ n µÄ¿é¡£ -
zip()?Óë?* ?ÔËËã·ûÏà½áºÏ¿ÉÒÔÓÃÀ´²ð½âÒ»¸öÁбí: >>>
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
ÔÚ 3.10 °æ¸ü¸Ä:?Ôö¼ÓÁË?strict ?²ÎÊý¡£
__import__(name,?globals=None,?locals=None,?fromlist=(),?level=0)
±¸×¢
Óë?importlib.import_module()?²»Í¬,ÕâÊÇÒ»¸öÈÕ³£ Python ±à³ÌÖв»ÐèÒªÓõ½µÄ¸ß¼¶º¯Êý¡£
´Ëº¯Êý»áÓÉ?import?Óï¾ä·¢Æðµ÷ÓᣠËü¿ÉÒÔ±»Ìæ»» (ͨ¹ýµ¼Èë?builtins?Ä£¿é²¢¸³Öµ¸ø?builtins.__import__ ) ÒÔ±ãÐÞ¸Ä?import ?Óï¾äµÄÓïÒå,µ«ÊÇ?Ç¿ÁÒ?²»½¨ÒéÕâÑù×ö,ÒòΪʹÓõ¼Èë¹³×Ó (²Î¼û?PEP 302) ͨ³£¸üÈÝÒ×ʵÏÖͬÑùµÄÄ¿±ê,²¢ÇÒ²»»áµ¼Ö´úÂëÎÊÌâ,ÒòΪÐí¶à´úÂ붼»á¼Ù¶¨ËùÓõÄÊÇĬÈÏʵÏÖ¡£ ͬÑùÒ²²»½¨ÒéÖ±½ÓʹÓÃ?__import__()?¶øÓ¦¸ÃÓÃ?importlib.import_module()¡£
±¾º¯Êý»áµ¼ÈëÄ£¿é?name,ÀûÓÃ?globals?ºÍ?locals?À´¾ö¶¨ÈçºÎÔÚ°üµÄÉÏÏÂÎÄÖнâÊ͸ÃÃû³Æ¡£fromlist?¸ø³öÁËÓ¦´Ó?name?Ä£¿éÖе¼ÈëµÄ¶ÔÏó»ò×ÓÄ£¿éµÄÃû³Æ¡£±ê×¼µÄʵÏÖ´úÂëÍêÈ«²»»áÓõ½?locals?²ÎÊý,Ö»Óõ½ÁË?globals?ÓÃÓÚÈ·¶¨?import?Óï¾äËùÔڵİüÉÏÏÂÎÄ¡£
level?Ö¸¶¨ÊÇʹÓþø¶Ô»¹ÊÇÏà¶Ôµ¼Èë¡£?0 ?(ĬÈÏÖµ) Òâζ׎öÖ´Ðоø¶Ôµ¼Èë¡£?level?ΪÕýÊýÖµ±íʾÏà¶ÔÓÚÄ£¿éµ÷ÓÃ?__import__()?µÄĿ¼,½«ÒªËÑË÷µÄ¸¸Ä¿Â¼²ãÊý (ÏêÇé²Î¼û?PEP 328)¡£
µ±?name?±äÁ¿µÄÐÎʽΪ?package.module ?ʱ,ͨ³£½«»á·µ»Ø×î¸ß²ã¼¶µÄ°ü(µÚÒ»¸öµãºÅ֮ǰµÄÃû³Æ),¶ø?²»ÊÇ?ÒÔ?name?ÃüÃûµÄÄ£¿é¡£ µ«ÊÇ,µ±¸ø³öÁË·Ç¿ÕµÄ?fromlist?²ÎÊýʱ,Ôò½«·µ»ØÒÔ?name?ÃüÃûµÄÄ£¿é¡£
ÀýÈç,Óï¾ä?import?spam ?µÄ½á¹û½«ÎªÓëÒÔÏ´úÂë×÷ÓÃÏàͬµÄ×Ö½ÚÂë:
spam = __import__('spam', globals(), locals(), [], 0)
Óï¾ä?import?spam.ham ?µÄ½á¹û½«ÎªÒÔϵ÷ÓÃ:
spam = __import__('spam.ham', globals(), locals(), [], 0)
Çë×¢ÒâÔÚÕâÀï?__import__()?ÊÇÈçºÎ·µ»Ø¶¥²ãÄ£¿éµÄ,ÒòΪÕâÊÇͨ¹ý?import?Óï¾ä±»°ó¶¨µ½Ìض¨Ãû³ÆµÄ¶ÔÏó¡£
ÁíÒ»·½Ãæ,Óï¾ä?from?spam.ham?import?eggs,?sausage?as?saus ?µÄ½á¹û½«Îª
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
ÔÚÕâÀï,?spam.ham ?Ä£¿é»áÓÉ?__import__()?·µ»Ø¡£ Òªµ¼ÈëµÄ¶ÔÏ󽫴Ӵ˶ÔÏóÖÐÌáÈ¡²¢¸³Öµ¸øËüÃǶÔÓ¦µÄÃû³Æ¡£
Èç¹ûÄúÖ»Ïë°´Ãû³Æµ¼ÈëÄ£¿é(¿ÉÄÜÔÚ°üÖÐ),ÇëʹÓÃ?importlib.import_module()
ÔÚ 3.3 °æ¸ü¸Ä:?level?µÄÖµ²»ÔÙÖ§³Ö¸ºÊý(ĬÈÏÖµÒ²ÐÞ¸ÄΪ0)¡£
ÔÚ 3.9 °æ¸ü¸Ä:?µ±Ê¹ÓÃÁËÃüÁîÐвÎÊý?-E?»ò?-I?ʱ,»·¾³±äÁ¿?PYTHONCASEOK?ÏÖÔÚ½«±»ºöÂÔ¡£
3.?Python ËÙÀÀ
ÏÂÃæµÄÀý×ÓÒÔÊÇ·ñÏÔʾÌáʾ·û(>>>?Óë?...)Çø·ÖÊäÈëÓëÊä³ö:ÊäÈëÀý×ÓÖеĴúÂëʱ,Òª¼üÈëÒÔÌáʾ·û¿ªÍ·µÄÐÐÖÐÌáʾ·ûºóµÄËùÓÐÄÚÈÝ;δÒÔÌáʾ·û¿ªÍ·µÄÐÐÊǽâÊÍÆ÷µÄÊä³ö¡£×¢Òâ,Àý×ÓÖеÄijÐгöÏֵĵڶþ¸öÌáʾ·ûÊÇÓÃÀ´½áÊø¶àÐÐÃüÁîµÄ,´Ëʱ,Òª¼üÈëÒ»¸ö¿Õ°×ÐС£
Äã¿ÉÒÔͨ¹ýÔÚʾÀý·½¿éÓÒÉϽǵÄ?>>> ?Éϵã»÷À´Çл»ÏÔʾÌáʾ·ûºÍÊä³ö¡£ Èç¹ûÄãÒþ²ØÁËÒ»¸öʾÀýµÄÌáʾ·ûºÍÊä³ö,ÄÇôÄã¿ÉÒÔ·½±ãµØ½«ÊäÈëÐи´ÖƲ¢Õ³Ìùµ½ÄãµÄ½âÊÍÆ÷ÖС£
±¾ÊÖ²áÖеÄÐí¶àÀý×Ó,ÉõÖÁ½»»¥Ê½ÃüÁ°üº¬×¢ÊÍ¡£Python ×¢ÊÍÒÔ?# ?¿ªÍ·,Ö±µ½¸ÃÎïÀíÐнáÊø¡£×¢ÊÍ¿ÉÒÔÔÚÐпªÍ·,»ò¿Õ°×·ûÓë´úÂëÖ®ºó,µ«²»ÄÜÔÚ×Ö·û´®ÀïÃæ¡£×Ö·û´®ÖÐµÄ # ºÅ¾ÍÊÇ # ºÅ¡£×¢ÊÍÓÃÓÚ²ûÃ÷´úÂë,Python ²»½âÊÍ×¢ÊÍ,¼üÈëÀý×Óʱ,¿ÉÒÔ²»ÊäÈë×¢ÊÍ¡£
ʾÀýÈçÏÂ:
# this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
3.1.?Python ÓÃ×÷¼ÆËãÆ÷
ÏÖÔÚ,³¢ÊÔһЩ¼òµ¥µÄ Python ÃüÁî¡£Æô¶¯½âÊÍÆ÷,µÈ´ýÖ÷Ìáʾ·û(>>> ?)³öÏÖ¡£
3.1.1.?Êý×Ö
½âÊÍÆ÷ÏñÒ»¸ö¼òµ¥µÄ¼ÆËãÆ÷:ÊäÈë±í´ïʽ,¾Í»á¸ø³ö´ð°¸¡£±í´ïʽµÄÓï·¨ºÜÖ±½Ó:ÔËËã·û?+ ¡¢- ¡¢* ¡¢/ ?µÄÓ÷¨ºÍÆäËû´ó²¿·ÖÓïÑÔÒ»Ñù(±ÈÈç,Pascal »ò C);À¨ºÅ (() ) ÓÃÀ´·Ö×é¡£ÀýÈç:
>>>
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
ÕûÊý(Èç,2 ¡¢4 ¡¢20 ?)µÄÀàÐÍÊÇ?int,´øСÊý(Èç,5.0 ¡¢1.6 ?)µÄÀàÐÍÊÇ?float¡£±¾½Ì³Ìºó°ë²¿·Ö½«½éÉܸü¶àÊý×ÖÀàÐÍ¡£
³ý·¨ÔËËã(/ )·µ»Ø¸¡µãÊý¡£ÓÃ?// ?ÔËËã·ûÖ´ÐÐ?floor division?µÄ½á¹ûÊÇÕûÊý(ºöÂÔСÊý);¼ÆËãÓàÊýÓÃ?% :
>>>
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder
17
Python ÓÃ?** ?ÔËËã·û¼ÆËã³Ë·½?1:
>>>
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
µÈºÅ(= )ÓÃÓÚ¸ø±äÁ¿¸³Öµ¡£¸³Öµºó,ÏÂÒ»¸ö½»»¥Ìáʾ·ûµÄλÖò»ÏÔʾÈκνá¹û:
>>>
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
Èç¹û±äÁ¿Î´¶¨Òå(¼´,δ¸³Öµ),ʹÓøñäÁ¿»áÌáʾ´íÎó:
>>>
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
Python È«ÃæÖ§³Ö¸¡µãÊý;»ìºÏÀàÐÍÔËËãÊýµÄÔËËã»á°ÑÕûÊýת»»Îª¸¡µãÊý:
>>>
>>> 4 * 3.75 - 1
14.0
½»»¥Ä£Ê½ÏÂ,ÉÏ´ÎÊä³öµÄ±í´ïʽ»á¸³¸ø±äÁ¿?_ ¡£°Ñ Python µ±×÷¼ÆËãÆ÷ʱ,ÓøñäÁ¿ÊµÏÖÏÂÒ»²½¼ÆËã¸ü¼òµ¥,ÀýÈç:
>>>
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
×îºÃ°Ñ¸Ã±äÁ¿µ±×÷Ö»¶ÁÀàÐÍ¡£²»ÒªÎªËüÏÔʽ¸³Öµ,·ñÔò»á´´½¨Ò»¸öͬÃû¶ÀÁ¢¾Ö²¿±äÁ¿,¸Ã±äÁ¿»áÓÃËüµÄħ·¨ÐÐΪÆÁ±ÎÄÚÖñäÁ¿¡£
³ýÁË?int?ºÍ?float,Python »¹Ö§³ÖÆäËûÊý×ÖÀàÐÍ,ÀýÈç?Decimal?»ò?Fraction¡£Python »¹ÄÚÖÃÖ§³Ö?¸´Êý,ºó׺?j ?»ò?J ?ÓÃÓÚ±íʾÐéÊý(ÀýÈç?3+5j ?)¡£
3.1.2.?×Ö·û´®
³ýÁËÊý×Ö,Python »¹¿ÉÒÔ²Ù×÷×Ö·û´®¡£×Ö·û´®ÓжàÖÖ±íÏÖÐÎʽ,Óõ¥ÒýºÅ('¡¡' )»òË«ÒýºÅ("¡¡" )±ê×¢µÄ½á¹ûÏàͬ?2¡£·´Ð±¸Ü?\ ?ÓÃÓÚתÒå:
>>>
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
½»»¥Ê½½âÊÍÆ÷»áΪÊä³öµÄ×Ö·û´®¼Ó×¢ÒýºÅ,ÌØÊâ×Ö·ûʹÓ÷´Ð±¸ÜתÒå¡£ËäÈ»,ÓÐʱÊä³öµÄ×Ö·û´®¿´ÆðÀ´ÓëÊäÈëµÄ×Ö·û´®²»Ò»Ñù(Íâ¼ÓµÄÒýºÅ¿ÉÄÜ»á¸Ä±ä),µ«Á½¸ö×Ö·û´®ÊÇÏàͬµÄ¡£Èç¹û×Ö·û´®ÖÐÓе¥ÒýºÅ¶øûÓÐË«ÒýºÅ,¸Ã×Ö·û´®Í⽫¼Óע˫ÒýºÅ,·´Ö®,Ôò¼Ó×¢µ¥ÒýºÅ¡£print()?º¯ÊýÊä³öµÄÄÚÈݸü¼ò½àÒ׶Á,Ëü»áÊ¡ÂÔÁ½±ßµÄÒýºÅ,²¢Êä³öתÒåºóµÄÌØÊâ×Ö·û:
>>>
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
Èç¹û²»Ï£ÍûÇ°ÖÃ?\ ?µÄ×Ö·ûתÒå³ÉÌØÊâ×Ö·û,¿ÉÒÔʹÓÃ?Ôʼ×Ö·û´®,ÔÚÒýºÅÇ°Ìí¼Ó?r ?¼´¿É:
>>>
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
×Ö·û´®×ÖÃæÖµ¿ÉÒÔ°üº¬¶àÐС£ Ò»ÖÖʵÏÖ·½Ê½ÊÇʹÓÃÈýÖØÒýºÅ:"""...""" ?»ò?'''...''' ¡£ ×Ö·û´®Öн«×Ô¶¯°üÀ¨ÐнáÊø·û,µ«Ò²¿ÉÒÔÔÚ»»Ðеĵط½Ìí¼ÓÒ»¸ö?\ ?À´±ÜÃâ´ËÇé¿ö¡£ ²Î¼ûÒÔÏÂʾÀý:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Êä³öÈçÏÂ(Çë×¢Ò⿪ʼµÄ»»ÐзûûÓб»°üÀ¨ÔÚÄÚ):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
×Ö·û´®¿ÉÒÔÓÃ?+ ?ºÏ²¢(Õ³µ½Ò»Æð),Ò²¿ÉÒÔÓÃ?* ?Öظ´:
>>>
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
ÏàÁÚµÄÁ½¸ö»ò¶à¸ö?×Ö·û´®×ÖÃæÖµ?(ÒýºÅ±ê×¢µÄ×Ö·û)»á×Ô¶¯ºÏ²¢:
>>>
>>> 'Py' 'thon'
'Python'
²ð·Ö³¤×Ö·û´®Ê±,Õâ¸ö¹¦ÄÜÌرðʵÓÃ:
>>>
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
ÕâÏÄÜÖ»ÄÜÓÃÓÚÁ½¸ö×ÖÃæÖµ,²»ÄÜÓÃÓÚ±äÁ¿»ò±í´ïʽ:
>>>
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^
SyntaxError: invalid syntax
ºÏ²¢¶à¸ö±äÁ¿,»òºÏ²¢±äÁ¿Óë×ÖÃæÖµ,ÒªÓÃ?+ :
>>>
>>> prefix + 'thon'
'Python'
×Ö·û´®Ö§³Ö?Ë÷Òý?(ϱê·ÃÎÊ),µÚÒ»¸ö×Ö·ûµÄË÷ÒýÊÇ 0¡£µ¥×Ö·ûûÓÐרÓõÄÀàÐÍ,¾ÍÊdz¤¶ÈΪһµÄ×Ö·û´®:
>>>
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
Ë÷Òý»¹Ö§³Ö¸ºÊý,ÓøºÊýË÷Òýʱ,´ÓÓұ߿ªÊ¼¼ÆÊý:
>>>
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
×¢Òâ,-0 ºÍ 0 Ò»Ñù,Òò´Ë,¸ºÊýË÷Òý´Ó -1 ¿ªÊ¼¡£
³ýÁËË÷Òý,×Ö·û´®»¹Ö§³Ö?ÇÐƬ¡£Ë÷Òý¿ÉÒÔÌáÈ¡µ¥¸ö×Ö·û,ÇÐƬ?ÔòÌáÈ¡×Ó×Ö·û´®:
>>>
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
ÇÐƬË÷ÒýµÄĬÈÏÖµºÜÓÐÓÃ;Ê¡ÂÔ¿ªÊ¼Ë÷Òýʱ,ĬÈÏֵΪ 0,Ê¡ÂÔ½áÊøË÷Òýʱ,ĬÈÏΪµ½×Ö·û´®µÄ½áβ:
>>>
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
×¢Òâ,Êä³ö½á¹û°üº¬ÇÐƬ¿ªÊ¼,µ«²»°üº¬ÇÐƬ½áÊø¡£Òò´Ë,s[:i]?+?s[i:] ?×ÜÊǵÈÓÚ?s :
>>>
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
»¹¿ÉÒÔÕâÑùÀí½âÇÐƬ,Ë÷ÒýÖ¸ÏòµÄÊÇ×Ö·û?Ö®¼ä?,µÚÒ»¸ö×Ö·ûµÄ×ó²à±êΪ 0,×îºóÒ»¸ö×Ö·ûµÄÓÒ²à±êΪ?n?,n?ÊÇ×Ö·û´®³¤¶È¡£ÀýÈç:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
µÚÒ»ÐÐÊý×ÖÊÇ×Ö·û´®ÖÐË÷Òý 0...6 µÄλÖÃ,µÚ¶þÐÐÊý×ÖÊǶÔÓ¦µÄ¸ºÊýË÷ÒýλÖá£i?µ½?j?µÄÇÐƬÓÉ?i?ºÍ?j?Ö®¼äËùÓжÔÓ¦µÄ×Ö·û×é³É¡£
¶ÔÓÚʹÓ÷ǸºË÷ÒýµÄÇÐƬ,Èç¹ûÁ½¸öË÷Òý¶¼²»Ô½½ç,ÇÐƬ³¤¶È¾ÍÊÇÆðÖ¹Ë÷ÒýÖ®²î¡£ÀýÈç,?word[1:3] ?µÄ³¤¶ÈÊÇ 2¡£
Ë÷ÒýÔ½½ç»á±¨´í:
>>>
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
µ«ÊÇ,ÇÐƬ»á×Ô¶¯´¦ÀíÔ½½çË÷Òý:
>>>
>>> word[4:42]
'on'
>>> word[42:]
''
Python ×Ö·û´®²»ÄÜÐÞ¸Ä,ÊÇ?immutable?µÄ¡£Òò´Ë,Ϊ×Ö·û´®ÖÐij¸öË÷ÒýλÖø³Öµ»á±¨´í:
>>>
>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
ÒªÉú³É²»Í¬µÄ×Ö·û´®,Ӧн¨Ò»¸ö×Ö·û´®:
>>>
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
ÄÚÖú¯Êý?len()?·µ»Ø×Ö·û´®µÄ³¤¶È:
>>>
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
²Î¼û
Îı¾ÐòÁÐÀàÐÍ --- str
×Ö·û´®ÊÇ?ÐòÁÐÀàÐÍ?,Ö§³ÖÐòÁÐÀàÐ͵ĸ÷ÖÖ²Ù×÷¡£
×Ö·û´®µÄ·½·¨
×Ö·û´®Ö§³ÖºÜ¶à±äÐÎÓë²éÕÒ·½·¨¡£
¸ñʽ×Ö·û´®×ÖÃæÖµ
ÄÚǶ±í´ïʽµÄ×Ö·û´®×ÖÃæÖµ¡£
¸ñʽ×Ö·û´®Óï·¨
ʹÓÃ?str.format()?¸ñʽ»¯×Ö·û´®¡£
printf ·ç¸ñµÄ×Ö·û´®¸ñʽ»¯
ÕâÀïÏêÊöÁËÓÃ?% ?ÔËËã·û¸ñʽ»¯×Ö·û´®µÄ²Ù×÷¡£
3.1.3.?Áбí
Python Ö§³Ö¶àÖÖ?¸´ºÏ?Êý¾ÝÀàÐÍ,¿É½«²»Í¬Öµ×éºÏÔÚÒ»Æð¡£×î³£ÓõÄ?Áбí?,ÊÇÓ÷½À¨ºÅ±ê×¢,¶ººÅ·Ö¸ôµÄÒ»×éÖµ¡£Áбí?¿ÉÒÔ°üº¬²»Í¬ÀàÐ͵ÄÔªËØ,µ«Ò»°ãÇé¿öÏÂ,¸÷¸öÔªËصÄÀàÐÍÏàͬ:
>>>
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
ºÍ×Ö·û´®(¼°ÆäËûÄÚÖÃ?sequence?ÀàÐÍ)Ò»Ñù,ÁбíÒ²Ö§³ÖË÷ÒýºÍÇÐƬ:
>>>
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
ÇÐƬ²Ù×÷·µ»Ø°üº¬ÇëÇóÔªËصÄÐÂÁÐ±í¡£ÒÔÏÂÇÐƬ²Ù×÷»á·µ»ØÁбíµÄ?dz¿½±´:
>>>
>>> squares[:]
[1, 4, 9, 16, 25]
ÁÐ±í»¹Ö§³ÖºÏ²¢²Ù×÷:
>>>
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Óë?immutable?×Ö·û´®²»Í¬, ÁбíÊÇ?mutable?ÀàÐÍ,ÆäÄÚÈÝ¿ÉÒԸıä:
>>>
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
append() ?·½·¨?¿ÉÒÔÔÚÁбí½áβÌí¼ÓÐÂÔªËØ(Ïê¼ûºóÎÄ):
>>>
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
ΪÇÐƬ¸³Öµ¿ÉÒԸıäÁбí´óС,ÉõÖÁÇå¿ÕÕû¸öÁбí:
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
ÄÚÖú¯Êý?len()?Ò²Ö§³ÖÁбí:
>>>
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
»¹¿ÉÒÔǶÌ×Áбí(´´½¨°üº¬ÆäËûÁбíµÄÁбí),ÀýÈç:
>>>
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
3.2.?×ßÏò±à³ÌµÄµÚÒ»²½
µ±È»,Python »¹¿ÉÒÔÍê³É±È¶þ¼Ó¶þ¸ü¸´ÔÓµÄÈÎÎñ¡£ ÀýÈç,¿ÉÒÔ±àд?ì³²¨ÄÇÆõÊýÁÐ?µÄ³õʼ×ÓÐòÁÐ,ÈçÏÂËùʾ:
>>>
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
±¾ÀýÒýÈëÁ˼¸¸öй¦ÄÜ¡£
-
µÚÒ»ÐÐÖеÄ?¶àÖظ³Öµ:±äÁ¿?a ?ºÍ?b ?ͬʱ»ñµÃÐÂÖµ 0 ºÍ 1¡£×îºóÒ»ÐÐÓÖÓÃÁËÒ»´Î¶àÖظ³Öµ,ÕâÌåÏÖÔÚÓÒ±í´ïʽÔÚ¸³ÖµÇ°¾ÍÒѾÇóÖµÁË¡£ÓÒ±í´ïʽÇóֵ˳ÐòΪ´Ó×óµ½ÓÒ¡£ -
while?Ñ»·Ö»ÒªÌõ¼þ(ÕâÀïÖ¸:a?<?10 )±£³ÖΪÕæ¾Í»áÒ»Ö±Ö´ÐС£Python ºÍ C Ò»Ñù,ÈκηÇÁãÕûÊý¶¼ÎªÕæ,ÁãΪ¼Ù¡£Õâ¸öÌõ¼þÒ²¿ÉÒÔÊÇ×Ö·û´®»òÁбíµÄÖµ,ÊÂʵÉÏ,ÈκÎÐòÁж¼¿ÉÒÔ;³¤¶È·ÇÁã¾ÍΪÕæ,¿ÕÐòÁÐÔòΪ¼Ù¡£Ê¾ÀýÖеÄÅжÏÖ»ÊÇ×î¼òµ¥µÄ±È½Ï¡£±È½Ï²Ù×÷·ûµÄ±ê׼д·¨ºÍ C ÓïÑÔÒ»Ñù:?< ?(СÓÚ)¡¢?> ?(´óÓÚ)¡¢?== ?(µÈÓÚ)¡¢?<= ?(СÓÚµÈÓÚ)¡¢?>= ?(´óÓÚµÈÓÚ)¼°?!= ?(²»µÈÓÚ)¡£ -
Ñ»·Ìå?ÊÇ?Ëõ½øµÄ?:Ëõ½øÊÇ Python ×éÖ¯Óï¾äµÄ·½Ê½¡£ÔÚ½»»¥Ê½ÃüÁîÐÐÀï,µÃΪÿ¸öËõÊäÈëÖƱí·û»ò¿Õ¸ñ¡£Ê¹ÓÃÎı¾±à¼Æ÷¿ÉÒÔʵÏÖ¸ü¸´ÔÓµÄÊäÈ뷽ʽ;ËùÓÐÏñÑùµÄÎı¾±à¼Æ÷¶¼Ö§³Ö×Ô¶¯Ëõ½ø¡£½»»¥Ê½ÊäÈ븴ºÏÓï¾äʱ, ÒªÔÚ×îºóÊäÈë¿Õ°×Ðбíʾ½áÊø(ÒòΪ½âÎöÆ÷²»ÖªµÀÄÄÒ»ÐдúÂëÊÇ×îºóÒ»ÐÐ)¡£×¢Òâ,ͬһ¿éÓï¾äµÄÿһÐеÄËõ½øÏàͬ¡£ -
print()?º¯ÊýÊä³ö¸ø¶¨²ÎÊýµÄÖµ¡£Óë±í´ïʽ²»Í¬(±ÈÈç,֮ǰ¼ÆËãÆ÷µÄÀý×Ó),ËüÄÜ´¦Àí¶à¸ö²ÎÊý,°üÀ¨¸¡µãÊýÓë×Ö·û´®¡£ËüÊä³öµÄ×Ö·û´®²»´øÒýºÅ,ÇÒ¸÷²ÎÊýÏîÖ®¼ä»á²åÈëÒ»¸ö¿Õ¸ñ,ÕâÑù¿ÉÒÔʵÏÖ¸üºÃµÄ¸ñʽ»¯²Ù×÷: >>> >>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
¹Ø¼ü×Ö²ÎÊý?end?¿ÉÒÔÈ¡ÏûÊä³öºóÃæµÄ»»ÐÐ, »òÓÃÁíÒ»¸ö×Ö·û´®½áβ: >>> >>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
±¸×¢
1
** ?±È?- ?µÄÓÅÏȼ¶¸ü¸ß, ËùÒÔ?-3**2 ?»á±»½âÊͳÉ?-(3**2) ?,Òò´Ë,½á¹ûÊÇ?-9 ¡£Òª±ÜÃâÕâ¸öÎÊÌâ,²¢Çҵõ½?9 , ¿ÉÒÔÓÃ?(-3)**2 ¡£
2
ºÍÆäËûÓïÑÔ²»Ò»Ñù,ÌØÊâ×Ö·ûÈç?\n ?ÔÚµ¥ÒýºÅ('...' )ºÍË«ÒýºÅ("..." )ÀïµÄÒâÒåÒ»Ñù¡£ÕâÁ½ÖÖÒýºÅΨһµÄÇø±ðÊÇ,²»ÐèÒªÔÚµ¥ÒýºÅÀïתÒåË«ÒýºÅ?" ,µ«±ØÐë°Ñµ¥ÒýºÅתÒå³É?\' ,·´Ö®ÒàÈ»¡£
4.?ÆäËûÁ÷³Ì¿ØÖƹ¤¾ß
³ýÁËÉÏÒ»Õ½éÉܵÄ?while?Óï¾ä,Python »¹Ö§³ÖÆäËûÓïÑÔÖг£¼ûµÄÁ÷³Ì¿ØÖÆÓï¾ä,Ö»ÊÇÉÔÓв»Í¬¡£
4.1.?if ?Óï¾ä
×îÈÃÈ˶úÊìÄÜÏêµÄÓ¦¸ÃÊÇ?if?Óï¾ä¡£ÀýÈç:
>>>
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More
if Óï¾ä°üº¬Áã¸ö»ò¶à¸ö?elif?×Ӿ估¿ÉÑ¡µÄ?else?×Ӿ䡣¹Ø¼ü×Ö 'elif ' ÊÇ 'else if' µÄËõд,ÊÊÓÃÓÚ±ÜÃâ¹ý¶àµÄËõ½ø¡£if ?...?elif ?...?elif ?... ÐòÁпÉÒÔµ±×÷ÆäËûÓïÑÔÖÐ?switch ?»ò?case ?Óï¾äµÄÌæ´úÆ·¡£
Èç¹ûÒª°ÑÒ»¸öÖµÓë¶à¸ö³£Á¿½øÐбȽÏ,»òÕß¼ì²éÌض¨ÀàÐÍ»òÊôÐÔ,match ?Óï¾ä¸üʵÓá£Ïê¼û?match Óï¾ä¡£
4.2.?for ?Óï¾ä
Python µÄ?for?Óï¾äÓë C »ò Pascal ÖеIJ»Í¬¡£Python µÄ?for ?Óï¾ä²»µü´úËãÊõµÝÔöÊýÖµ(Èç Pascal),»òÊǸøÓèÓû§¶¨Òåµü´ú²½ÖèºÍÔÝÍ£Ìõ¼þµÄÄÜÁ¦(Èç C),¶øÊǵü´úÁбí»ò×Ö·û´®µÈÈÎÒâÐòÁÐ,ÔªËصĵü´ú˳ÐòÓëÔÚÐòÁÐÖгöÏÖµÄ˳ÐòÒ»Ö¡£ ÀýÈç:
>>>
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
±éÀú¼¯ºÏʱÐ޸ļ¯ºÏµÄÄÚÈÝ,»áºÜÈÝÒ×Éú³É´íÎóµÄ½á¹û¡£Òò´Ë²»ÄÜÖ±½Ó½øÐÐÑ»·,¶øÊÇÓ¦±éÀú¸Ã¼¯ºÏµÄ¸±±¾»ò´´½¨Ðµļ¯ºÏ:
# Create a sample collection
users = {'Hans': 'active', '¨¦l¨¦onore': 'inactive', '¾°Ì«ÀÉ': 'active'}
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
ÄÚÖú¯Êý?range()?³£ÓÃÓÚ±éÀúÊý×ÖÐòÁÐ,¸Ãº¯Êý¿ÉÒÔÉú³ÉËãÊõ¼¶Êý:
>>>
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
Éú³ÉµÄÐòÁв»°üº¬¸ø¶¨µÄÖÕÖ¹ÊýÖµ;range(10) ?Éú³É 10 ¸öÖµ,ÕâÊÇÒ»¸ö³¤¶ÈΪ 10 µÄÐòÁÐ,ÆäÖеÄÔªËØË÷Òý¶¼ÊǺϷ¨µÄ¡£range ¿ÉÒÔ²»´Ó 0 ¿ªÊ¼,»¹¿ÉÒÔ°´Ö¸¶¨·ù¶ÈµÝÔö(µÝÔö·ù¶È³ÆΪ '²½½ø',Ö§³Ö¸ºÊý):
>>>
>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(-10, -100, -30))
[-10, -40, -70]
range()?ºÍ?len()?×éºÏÔÚÒ»Æð,¿ÉÒÔ°´Ë÷Òýµü´úÐòÁÐ:
>>>
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
²»¹ý,´ó¶àÊýÇé¿öÏÂ,enumerate()?º¯Êý¸ü±ã½Ý,Ïê¼û?Ñ»·µÄ¼¼ÇÉ?¡£
Èç¹ûÖ»Êä³ö range,»á³öÏÖÒâÏë²»µ½µÄ½á¹û:
>>>
>>> range(10)
range(0, 10)
range()?·µ»Ø¶ÔÏóµÄ²Ù×÷ºÍÁбíºÜÏñ,µ«ÆäʵÕâÁ½ÖÖ¶ÔÏó²»ÊÇÒ»»ØÊ¡£µü´úʱ,¸Ã¶ÔÏó»ùÓÚËùÐèÐòÁзµ»ØÁ¬ÐøÏî,²¢Ã»ÓÐÉú³ÉÕæÕýµÄÁбí,´Ó¶ø½ÚÊ¡Á˿ռ䡣
ÕâÖÖ¶ÔÏó³ÆΪ¿Éµü´ú¶ÔÏó?iterable,º¯Êý»ò³ÌÐò½á¹¹¿Éͨ¹ý¸Ã¶ÔÏó»ñÈ¡Á¬ÐøÏî,Ö±µ½ËùÓÐÔªËØÈ«²¿µü´úÍê±Ï¡£for?Óï¾ä¾ÍÊÇÕâÑùµÄ¼Ü¹¹,sum()?ÊÇÒ»Öְѿɵü´ú¶ÔÏó×÷Ϊ²ÎÊýµÄº¯Êý:
>>>
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
ÏÂÎĽ«½éÉܸü¶à·µ»Ø¿Éµü´ú¶ÔÏó»ò°Ñ¿Éµü´ú¶ÔÏóµ±×÷²ÎÊýµÄº¯Êý¡£ ÔÚ?Êý¾Ý½á¹¹?ÕâÒ»Õ½ÚÖÐ,ÎÒÃǽ«ÌÖÂÛÓйØ?list()?µÄ¸ü¶àϸ½Ú¡£
4.4.?Ñ»·ÖеÄ?break ¡¢continue ?Óï¾ä¼°?else ?×Ó¾ä
break?Óï¾äºÍ C ÖеÄÀàËÆ,ÓÃÓÚÌø³ö×î½üµÄ?for?»ò?while?Ñ»·¡£
Ñ»·Óï¾äÖ§³Ö?else ?×Ó¾ä;for?Ñ»·ÖÐ,¿Éµü´ú¶ÔÏóÖеÄÔªËØÈ«²¿Ñ»·Íê±Ï,»ò?while?Ñ»·µÄÌõ¼þΪ¼Ùʱ,Ö´ÐиÃ×Ó¾ä;break?Óï¾äÖÕֹѻ·Ê±,²»Ö´ÐиÃ×Ӿ䡣 Çë¿´ÏÂÃæÕâ¸ö²éÕÒËØÊýµÄÑ»·Ê¾Àý:
>>>
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
(û´í,Õâ¶Î´úÂë¾ÍÊÇÕâôд¡£×Ðϸ¿´:else ?×Ó¾äÊôÓÚ?for?Ñ»·,²»ÊôÓÚ?if?Óï¾ä¡£)
Óë?if?Óï¾äÏà±È,Ñ»·µÄ?else ?×Ó¾ä¸üÏñ?try?µÄ?else ?×Ó¾ä:?try?µÄ?else ?×Ó¾äÔÚδ´¥·¢Ò쳣ʱִÐÐ,Ñ»·µÄ?else ?×Ó¾äÔòÔÚδÔËÐÐ?break ?ʱִÐС£try ?Óï¾äºÍÒì³£Ïê¼û?Òì³£µÄ´¦Àí¡£
continue?Óï¾äÒ²½è¼ø×Ô C ÓïÑÔ,±íʾ¼ÌÐøÖ´ÐÐÑ»·µÄÏÂÒ»´Îµü´ú:
>>>
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
4.5.?pass ?Óï¾ä
pass?Óï¾ä²»Ö´ÐÐÈκβÙ×÷¡£Óï·¨ÉÏÐèÒªÒ»¸öÓï¾ä,µ«³ÌÐò²»Êµ¼ÊÖ´ÐÐÈκζ¯×÷ʱ,¿ÉÒÔʹÓøÃÓï¾ä¡£ÀýÈç:
>>>
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
ÏÂÃæÕâ¶Î´úÂë´´½¨ÁËÒ»¸ö×îСµÄÀà:
>>>
>>> class MyEmptyClass:
... pass
...
pass?»¹¿ÉÒÔÓÃ×÷º¯Êý»òÌõ¼þ×Ó¾äµÄռλ·û,Èÿª·¢Õß¾Û½¹¸ü³éÏóµÄ²ã´Î¡£´Ëʱ,³ÌÐòÖ±½ÓºöÂÔ?pass :
>>>
>>> def initlog(*args):
... pass # Remember to implement this!
...
4.6.?match ?Óï¾ä
A?match?statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it's more similar to pattern matching in languages like Rust or Haskell. Only the first pattern that matches gets executed and it can also extract components (sequence elements or object attributes) from the value into variables.
×î¼òµ¥µÄÐÎʽÊǽ«Ò»¸öÄ¿±êÖµÓëÒ»¸ö»ò¶à¸ö×ÖÃæÖµ½øÐбȽÏ:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
×¢Òâ×îºóÒ»¸ö´úÂë¿é:¡°±äÁ¿Ãû¡±?_ ?±»×÷Ϊ?ͨÅä·û?²¢±Ø¶¨»áÆ¥Åä³É¹¦¡£ Èç¹ûûÓÐ case Óï¾äÆ¥Åä³É¹¦,Ôò²»»áÖ´ÐÐÈκηÖÖ§¡£
ʹÓÃ?| ?(¡° or ¡±)ÔÚÒ»¸öģʽÖпÉÒÔ×éºÏ¶à¸ö×ÖÃæÖµ:
case 401 | 403 | 404:
return "Not allowed"
ģʽµÄÐÎʽÀàËƽâ°ü¸³Öµ,²¢¿É±»ÓÃÓڰ󶨱äÁ¿:
# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
Çë×ÐϸÑо¿´Ë´úÂë! µÚÒ»¸öģʽÓÐÁ½¸ö×ÖÃæÖµ,¿ÉÒÔ¿´×÷ÊÇÉÏÃæËùʾ×ÖÃæֵģʽµÄÀ©Õ¹¡£µ«½ÓÏÂÀ´µÄÁ½¸öģʽ½áºÏÁËÒ»¸ö×ÖÃæÖµºÍÒ»¸ö±äÁ¿,¶ø±äÁ¿?°ó¶¨?ÁËÒ»¸öÀ´×ÔÄ¿±êµÄÖµ(point )¡£µÚËĸöģʽ²¶»ñÁËÁ½¸öÖµ,ÕâʹµÃËüÔÚ¸ÅÄîÉÏÀàËÆÓÚ½â°ü¸³Öµ?(x,?y)?=?point ¡£
Èç¹ûʹÓÃÀàʵÏÖÊý¾Ý½á¹¹,¿ÉÔÚÀàÃûºó¼ÓÒ»¸öÀàËÆÓÚ¹¹ÔìÆ÷µÄ²ÎÊýÁбí,ÕâÑù×ö¿ÉÒÔ°ÑÊôÐԷŵ½±äÁ¿Àï:
class Point:
x: int
y: int
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")
¿ÉÔÚ dataclass µÈÖ§³ÖÊôÐÔÅÅÐòµÄÄÚÖÃÀàÖÐʹÓÃλÖòÎÊý¡£»¹¿ÉÔÚÀàÖÐÉèÖÃ?__match_args__ ?ÌØÊâÊôÐÔΪģʽµÄÊôÐÔ¶¨ÒåÖ¸¶¨Î»Öá£Èç¹ûËü±»ÉèΪ ("x", "y"),ÔòÒÔÏÂģʽ¾ùΪµÈ¼ÛµÄ,²¢ÇÒ¶¼°Ñ?y ?ÊôÐ԰󶨵½?var ?±äÁ¿:
Point(1, var)
Point(1, y=var)
Point(x=1, y=var)
Point(y=var, x=1)
¶ÁȡģʽµÄÍƼö·½Ê½Êǽ«ËüÃÇ¿´×öÊÇÄã»áÔÚ¸³Öµ²Ù×÷×ó²à·ÅÖõÄÄÚÈݵÄÀ©Õ¹ÐÎʽ,ÒÔ±ãÀí½â¸÷¸ö±äÁ¿½«»á±»ÉèÖõÄÖµ¡£ Ö»Óе¥¶ÀµÄÃû³Æ(ÀýÈçÉÏÃæµÄ?var )»á±» match Óï¾äËù¸³Öµ¡£ ´øµãºÅµÄÃû³Æ (ÀýÈç?foo.bar )¡¢ÊôÐÔÃû³Æ(ÀýÈçÉÏÃæµÄ?x= ?ºÍ?y= )»òÀàÃû³Æ(ͨ¹ýÆäºóµÄ "(...)" À´Ê¶±ð,ÀýÈçÉÏÃæµÄ?Point )¶¼¾ø²»»á±»¸³Öµ¡£
ģʽ¿ÉÒÔÈÎÒâµØǶÌס£ÀýÈç,Èç¹ûÓÐÒ»¸öÓɵã×é³ÉµÄ¶ÌÁбí,Ôò¿ÉʹÓÃÈçÏ·½Ê½½øÐÐÆ¥Åä:
match points:
case []:
print("No points")
case [Point(0, 0)]:
print("The origin")
case [Point(x, y)]:
print(f"Single point {x}, {y}")
case [Point(0, y1), Point(0, y2)]:
print(f"Two on the Y axis at {y1}, {y2}")
case _:
print("Something else")
ΪģʽÌí¼Ó³ÉΪÊØ»¤ÏîµÄ?if ?×Ӿ䡣Èç¹ûÊØ»¤ÏîµÄֵΪ¼Ù,Ôò?match ?¼ÌÐøÆ¥ÅäÏÂÒ»¸ö case Óï¾ä¿é¡£×¢Òâ,ÖµµÄ²¶»ñ·¢ÉúÔÚÊØ»¤Ïî±»Çóֵ֮ǰ:
match point:
case Point(x, y) if x == y:
print(f"Y=X at {x}")
case Point(x, y):
print(f"Not on the diagonal")
match Óï¾äµÄÆäËûÌØÐÔ:
-
Óë½â°ü¸³ÖµÀàËÆ,Ôª×éºÍÁбíģʽ¾ßÓÐÍêÈ«ÏàͬµÄº¬Òå,²¢ÇÒʵ¼ÊÉÏÄÜÆ¥ÅäÈÎÒâÐòÁС£ µ«ËüÃDz»ÄÜÆ¥Åäµü´úÆ÷»ò×Ö·û´®¡£ -
ÐòÁÐģʽ֧³ÖÀ©Õ¹½â°ü²Ù×÷:[x,?y,?*rest] ?ºÍ?(x,?y,?*rest) ?µÄ×÷ÓÃÀàËÆÓÚ½â°ü¸³Öµ¡£ ÔÚ?* ?Ö®ºóµÄÃû³ÆÒ²¿ÉÒÔΪ?_ ,Òò´Ë,(x,?y,?*_) ?¿ÉÒÔÆ¥Åä°üº¬ÖÁÉÙÁ½¸öÌõÄ¿µÄÐòÁÐ,¶ø²»±Ø°ó¶¨ÆäÓàµÄÌõÄ¿¡£ -
Ó³Éäģʽ:{"bandwidth":?b,?"latency":?l} ?´Ó×ÖµäÖⶻñ?"bandwidth" ?ºÍ?"latency" ?µÄÖµ¡£ÓëÐòÁÐģʽ²»Í¬,¶îÍâµÄ¼ü»á±»ºöÂÔ¡£**rest ?µÈ½â°ü²Ù×÷Ò²Ö§³Ö¡£µ«?**_ ?ÊÇÈßÓàµÄ,²»ÔÊÐíʹÓᣠ-
ʹÓÃ?as ?¹Ø¼ü×Ö¿ÉÒÔ²¶»ñ×Óģʽ: case (Point(x1, y1), Point(x2, y2) as p2): ...
½«°ÑÊäÈëµÄµÚ¶þ¸öÔªËز¶»ñΪ?p2 ?(Ö»ÒªÊäÈëÊÇ°üº¬Á½¸öµãµÄÐòÁÐ) -
´ó¶àÊý×ÖÃæÖµÊÇ°´ÏàµÈÐԱȽϵÄ,µ«Êǵ¥Àý¶ÔÏó?True ,?False ?ºÍ?None ?ÔòÊÇ°´±êʶºÅ±È½ÏµÄ¡£ -
ģʽ¿ÉÒÔʹÓÃÃüÃû³£Á¿¡£ ÕâЩÃüÃû³£Á¿±ØÐëΪ´øµãºÅµÄÃû³ÆÒÔ·ÀÖ¹ËüÃDZ»½â¶ÁΪ²¶»ñ±äÁ¿: from enum import Enum
class Color(Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))
match color:
case Color.RED:
print("I see red!")
case Color.GREEN:
print("Grass is green")
case Color.BLUE:
print("I'm feeling the blues :(")
Òª»ñÈ¡¸üÏêϸµÄ˵Ã÷ºÍ¶îÍâµÄʾÀý,Äã¿ÉÒÔ²ÎÔÄÒԽ̸̳ñʽ׫дµÄ?PEP 636¡£
4.7.?¶¨Ò庯Êý
ÏÂÁдúÂë´´½¨Ò»¸ö¿ÉÒÔÊä³öÏÞ¶¨ÊýÖµÄÚµÄì³²¨ÄÇÆõÊýÁк¯Êý:
>>>
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
¶¨Òå?º¯ÊýʹÓùؼü×Ö?def,ºó¸úº¯ÊýÃûÓëÀ¨ºÅÄÚµÄÐβÎÁÐ±í¡£º¯ÊýÓï¾ä´ÓÏÂÒ»ÐпªÊ¼,²¢ÇÒ±ØÐëËõ½ø¡£
º¯ÊýÄڵĵÚÒ»ÌõÓï¾äÊÇ×Ö·û´®Ê±,¸Ã×Ö·û´®¾ÍÊÇÎĵµ×Ö·û´®,Ò²³ÆΪ?docstring,Ïê¼û?Îĵµ×Ö·û´®¡£ÀûÓÃÎĵµ×Ö·û´®¿ÉÒÔ×Ô¶¯Éú³ÉÔÚÏßÎĵµ»ò´òÓ¡°æÎĵµ,»¹¿ÉÒÔÈÿª·¢ÕßÔÚä¯ÀÀ´úÂëʱֱ½Ó²éÔÄÎĵµ;Python ¿ª·¢Õß×îºÃÑø³ÉÔÚ´úÂëÖмÓÈëÎĵµ×Ö·û´®µÄºÃÏ°¹ß¡£
º¯ÊýÔÚ?Ö´ÐÐ?ʱʹÓú¯Êý¾Ö²¿±äÁ¿·ûºÅ±í,ËùÓк¯Êý±äÁ¿¸³Öµ¶¼´æÔÚ¾Ö²¿·ûºÅ±íÖÐ;ÒýÓñäÁ¿Ê±,Ê×ÏÈ,ÔÚ¾Ö²¿·ûºÅ±íÀï²éÕÒ±äÁ¿,È»ºó,ÊÇÍâ²ãº¯Êý¾Ö²¿·ûºÅ±í,ÔÙÊÇÈ«¾Ö·ûºÅ±í,×îºóÊÇÄÚÖÃÃû³Æ·ûºÅ±í¡£Òò´Ë,¾¡¹Ü¿ÉÒÔÒýÓÃÈ«¾Ö±äÁ¿ºÍÍâ²ãº¯ÊýµÄ±äÁ¿,µ«×îºÃ²»ÒªÔÚº¯ÊýÄÚÖ±½Ó¸³Öµ(³ý·ÇÊÇ?global?Óï¾ä¶¨ÒåµÄÈ«¾Ö±äÁ¿,»ò?nonlocal?Óï¾ä¶¨ÒåµÄÍâ²ãº¯Êý±äÁ¿)¡£
ÔÚµ÷Óú¯Êýʱ»á½«Êµ¼Ê²ÎÊý(ʵ²Î)ÒýÈëµ½±»µ÷Óú¯ÊýµÄ¾Ö²¿·ûºÅ±íÖÐ;Òò´Ë,ʵ²ÎÊÇʹÓÃ?°´Öµµ÷ÓÃ?À´´«µÝµÄ(ÆäÖеÄ?Öµ?ʼÖÕÊǶÔÏóµÄ?ÒýÓÃ?¶ø²»ÊǶÔÏóµÄÖµ)¡£?1?µ±Ò»¸öº¯Êýµ÷ÓÃÁíÍâÒ»¸öº¯Êýʱ,»áΪ¸Ãµ÷Óô´½¨Ò»¸öеľֲ¿·ûºÅ±í¡£
º¯Êý¶¨ÒåÔÚµ±Ç°·ûºÅ±íÖаѺ¯ÊýÃûÓ뺯Êý¶ÔÏó¹ØÁªÔÚÒ»Æð¡£½âÊÍÆ÷°Ñº¯ÊýÃûÖ¸ÏòµÄ¶ÔÏó×÷ΪÓû§×Ô¶¨Ò庯Êý¡£»¹¿ÉÒÔʹÓÃÆäËûÃû³ÆÖ¸Ïòͬһ¸öº¯Êý¶ÔÏó,²¢·ÃÎʷøú¯Êý:
>>>
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
fib ?²»·µ»ØÖµ,Òò´Ë,ÆäËûÓïÑÔ²»°ÑËüµ±×÷º¯Êý,¶øÊǵ±×÷¹ý³Ì¡£ÊÂʵÉÏ,ûÓÐ?return?Óï¾äµÄº¯ÊýÒ²·µ»ØÖµ,Ö»²»¹ýÕâ¸öÖµ±È½ÏÊÇ?None ?(ÊÇÒ»¸öÄÚÖÃÃû³Æ)¡£Ò»°ãÀ´Ëµ,½âÊÍÆ÷²»»áÊä³öµ¥¶ÀµÄ·µ»ØÖµ?None ?,ÈçÐè²é¿´¸ÃÖµ,¿ÉÒÔʹÓÃ?print():
>>>
>>> fib(0)
>>> print(fib(0))
None
±àд²»Ö±½ÓÊä³öì³²¨ÄÇÆõÊýÁÐÔËËã½á¹û,¶øÊÇ·µ»ØÔËËã½á¹ûÁбíµÄº¯ÊýÒ²·Ç³£¼òµ¥:
>>>
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
±¾ÀýÒ²ÐÂÒýÈëÁËһЩ Python ¹¦ÄÜ:
-
return?Óï¾ä·µ»Øº¯ÊýµÄÖµ¡£return ?Óï¾ä²»´ø±í´ïʽ²ÎÊýʱ,·µ»Ø?None ¡£º¯ÊýÖ´ÐÐÍê±ÏÍ˳öÒ²·µ»Ø?None ¡£ -
result.append(a) ?Óï¾äµ÷ÓÃÁËÁбí¶ÔÏó?result ?µÄ?·½·¨?¡£·½·¨ÊÇ¡°´ÓÊôÓÚ¡±¶ÔÏóµÄº¯Êý,ÃüÃûΪ?obj.methodname ,obj ?ÊǶÔÏó(Ò²¿ÉÒÔÊDZí´ïʽ),methodname ?ÊǶÔÏóÀàÐͶ¨ÒåµÄ·½·¨Ãû¡£²»Í¬ÀàÐͶ¨Ò岻ͬµÄ·½·¨,²»Í¬ÀàÐ͵ķ½·¨Ãû¿ÉÒÔÏàͬ,ÇÒ²»»áÒýÆðÆçÒå¡£(ÓÃ?Àà?¿ÉÒÔ×Ô¶¨Òå¶ÔÏóÀàÐͺͷ½·¨,Ïê¼û?Àà?)ʾÀýÖеķ½·¨?append() ?ÊÇΪÁбí¶ÔÏó¶¨ÒåµÄ,ÓÃÓÚÔÚÁбíĩβÌí¼ÓÐÂÔªËØ¡£±¾ÀýÖÐ,¸Ã·½·¨Ï൱ÓÚ?result?=?result?+?[a] ?,µ«¸üÓÐЧ¡£
4.8.?º¯Êý¶¨ÒåÏê½â
º¯Êý¶¨ÒåÖ§³Ö¿É±äÊýÁ¿µÄ²ÎÊý¡£ÕâÀïÁгöÈýÖÖ¿ÉÒÔ×éºÏʹÓõÄÐÎʽ¡£
4.8.1.?ĬÈÏÖµ²ÎÊý
Ϊ²ÎÊýÖ¸¶¨Ä¬ÈÏÖµÊǷdz£ÓÐÓõķ½Ê½¡£µ÷Óú¯Êýʱ,¿ÉÒÔʹÓñȶ¨Òåʱ¸üÉٵIJÎÊý,ÀýÈç:
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
¸Ãº¯Êý¿ÉÒÔÓÃÒÔÏ·½Ê½µ÷ÓÃ:
-
Ö»¸ø³ö±Øѡʵ²Î:ask_ok('Do?you?really?want?to?quit?') -
¸ø³öÒ»¸ö¿Éѡʵ²Î:ask_ok('OK?to?overwrite?the?file?',?2) -
¸ø³öËùÓÐʵ²Î:ask_ok('OK?to?overwrite?the?file?',?2,?'Come?on,?only?yes?or?no!')
±¾Àý»¹Ê¹ÓÃÁ˹ؼü×Ö?in?,ÓÃÓÚÈ·ÈÏÐòÁÐÖÐÊÇ·ñ°üº¬Ä³¸öÖµ¡£
ĬÈÏÖµÔÚ?¶¨Òå?×÷ÓÃÓòÀïµÄº¯Êý¶¨ÒåÖÐÇóÖµ,ËùÒÔ:
i = 5
def f(arg=i):
print(arg)
i = 6
f()
ÉÏÀýÊä³öµÄÊÇ?5 ¡£
ÖØÒª¾¯¸æ:?ĬÈÏÖµÖ»¼ÆËãÒ»´Î¡£Ä¬ÈÏֵΪÁÐ±í¡¢×Öµä»òÀàʵÀýµÈ¿É±ä¶ÔÏóʱ,»á²úÉúÓë¸Ã¹æÔò²»Í¬µÄ½á¹û¡£ÀýÈç,ÏÂÃæµÄº¯Êý»áÀÛ»ýºóÐøµ÷ÓÃʱ´«µÝµÄ²ÎÊý:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
Êä³ö½á¹ûÈçÏÂ:
[1]
[1, 2]
[1, 2, 3]
²»ÏëÔÚºóÐøµ÷ÓÃÖ®¼ä¹²ÏíĬÈÏֵʱ,Ó¦ÒÔÈçÏ·½Ê½±àдº¯Êý:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
4.8.2.?¹Ø¼ü×Ö²ÎÊý
kwarg=value ?ÐÎʽµÄ?¹Ø¼ü×Ö²ÎÊý?Ò²¿ÉÒÔÓÃÓÚµ÷Óú¯Êý¡£º¯ÊýʾÀýÈçÏÂ:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
¸Ãº¯Êý½ÓÊÜÒ»¸ö±ØÑ¡²ÎÊý(voltage )ºÍÈý¸ö¿ÉÑ¡²ÎÊý(state ,?action ?ºÍ?type )¡£¸Ãº¯Êý¿ÉÓÃÏÂÁз½Ê½µ÷ÓÃ:
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
ÒÔϵ÷Óú¯ÊýµÄ·½Ê½¶¼ÎÞЧ:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument
º¯Êýµ÷ÓÃʱ,¹Ø¼ü×Ö²ÎÊý±ØÐë¸úÔÚλÖòÎÊýºóÃæ¡£ËùÓд«µÝµÄ¹Ø¼ü×Ö²ÎÊý¶¼±ØÐëÆ¥ÅäÒ»¸öº¯Êý½ÓÊܵIJÎÊý(±ÈÈç,actor ?²»ÊǺ¯Êý?parrot ?µÄÓÐЧ²ÎÊý),¹Ø¼ü×Ö²ÎÊýµÄ˳Ðò²¢²»ÖØÒª¡£ÕâÒ²°üÀ¨±ØÑ¡²ÎÊý,(±ÈÈç,parrot(voltage=1000) ?Ò²ÓÐЧ)¡£²»ÄܶÔͬһ¸ö²ÎÊý¶à´Î¸³Öµ,ÏÂÃæ¾ÍÊÇÒ»¸öÒò´ËÏÞÖƶøʧ°ÜµÄÀý×Ó:
>>>
>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'
×îºóÒ»¸öÐβÎΪ?**name ?ÐÎʽʱ,½ÓÊÕÒ»¸ö×Öµä(Ïê¼û?Ó³ÉäÀàÐÍ --- dict),¸Ã×Öµä°üº¬Ó뺯ÊýÖÐÒѶ¨ÒåÐβζÔÓ¦Ö®ÍâµÄËùÓйؼü×Ö²ÎÊý¡£**name ?ÐβοÉÒÔÓë?*name ?ÐβÎ(ÏÂһС½Ú½éÉÜ)×éºÏʹÓÃ(*name ?±ØÐëÔÚ?**name ?Ç°Ãæ),?*name ?ÐβνÓÊÕÒ»¸ö?Ôª×é,¸ÃÔª×é°üº¬ÐβÎÁбíÖ®ÍâµÄλÖòÎÊý¡£ÀýÈç,¿ÉÒÔ¶¨ÒåÏÂÃæÕâÑùµÄº¯Êý:
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
¸Ãº¯Êý¿ÉÒÔÓÃÈçÏ·½Ê½µ÷ÓÃ:
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
Êä³ö½á¹ûÈçÏÂ:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
×¢Òâ,¹Ø¼ü×Ö²ÎÊýÔÚÊä³ö½á¹ûÖеÄ˳ÐòÓëµ÷Óú¯ÊýʱµÄ˳ÐòÒ»Ö¡£
4.8.3.?ÌØÊâ²ÎÊý
ĬÈÏÇé¿öÏÂ,²ÎÊý¿ÉÒÔ°´Î»ÖûòÏÔʽ¹Ø¼ü×Ö´«µÝ¸ø Python º¯Êý¡£ÎªÁËÈôúÂëÒ׶Á¡¢¸ßЧ,×îºÃÏÞÖƲÎÊýµÄ´«µÝ·½Ê½,ÕâÑù,¿ª·¢ÕßÖ»Ðè²é¿´º¯Êý¶¨Òå,¼´¿ÉÈ·¶¨²ÎÊýÏîÊǽö°´Î»Öᢰ´Î»Öûò¹Ø¼ü×Ö,»¹Êǽö°´¹Ø¼ü×Ö´«µÝ¡£
º¯Êý¶¨ÒåÈçÏÂ:
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
----------- ---------- ----------
| | |
| Positional or keyword |
| - Keyword only
-- Positional only
/ ?ºÍ?* ?ÊÇ¿ÉÑ¡µÄ¡£ÕâЩ·ûºÅ±íÃ÷ÐβÎÈçºÎ°Ñ²ÎÊýÖµ´«µÝ¸øº¯Êý:λÖá¢Î»Öûò¹Ø¼ü×Ö¡¢¹Ø¼ü×Ö¡£¹Ø¼ü×ÖÐβÎÒ²½Ð×÷ÃüÃûÐβΡ£
4.8.3.1.?λÖûò¹Ø¼ü×Ö²ÎÊý
º¯Êý¶¨ÒåÖÐδʹÓÃ?/ ?ºÍ?* ?ʱ,²ÎÊý¿ÉÒÔ°´Î»Öûò¹Ø¼ü×Ö´«µÝ¸øº¯Êý¡£
4.8.3.2.?½öλÖòÎÊý
´Ë´¦ÔÙ½éÉÜһЩϸ½Ú,Ìض¨ÐβοÉÒÔ±ê¼ÇΪ?½öÏÞλÖ᣽öÏÞλÖÃ?ʱ,ÐβεÄ˳ÐòºÜÖØÒª,ÇÒÕâЩÐββ»ÄÜÓùؼü×Ö´«µÝ¡£½öÏÞλÖÃÐβÎÓ¦·ÅÔÚ?/ ?(Õýб¸Ü)Ç°¡£/ ?ÓÃÓÚÔÚÂß¼ÉÏ·Ö¸î½öÏÞλÖÃÐβÎÓëÆäËüÐβΡ£Èç¹ûº¯Êý¶¨ÒåÖÐûÓÐ?/ ,Ôò±íʾûÓнöÏÞλÖÃÐβΡ£
/ ?ºó¿ÉÒÔÊÇ?λÖûò¹Ø¼ü×Ö?»ò?½öÏ޹ؼü×Ö?ÐβΡ£
4.8.3.3.?½öÏ޹ؼü×Ö²ÎÊý
°ÑÐβαê¼ÇΪ?½öÏ޹ؼü×Ö,±íÃ÷±ØÐëÒԹؼü×Ö²ÎÊýÐÎʽ´«µÝ¸ÃÐβÎ,Ó¦ÔÚ²ÎÊýÁбíÖеÚÒ»¸ö?½öÏ޹ؼü×Ö?ÐβÎÇ°Ìí¼Ó?* ¡£
4.8.3.4.?º¯ÊýʾÀý
Çë¿´ÏÂÃæµÄº¯Êý¶¨ÒåʾÀý,×¢Òâ?/ ?ºÍ?* ?±ê¼Ç:
>>>
>>> def standard_arg(arg):
... print(arg)
...
>>> def pos_only_arg(arg, /):
... print(arg)
...
>>> def kwd_only_arg(*, arg):
... print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
... print(pos_only, standard, kwd_only)
µÚÒ»¸öº¯Êý¶¨Òå?standard_arg ?ÊÇ×î³£¼ûµÄÐÎʽ,¶Ôµ÷Ó÷½Ê½Ã»ÓÐÈκÎÏÞÖÆ,¿ÉÒÔ°´Î»ÖÃÒ²¿ÉÒÔ°´¹Ø¼ü×Ö´«µÝ²ÎÊý:
>>>
>>> standard_arg(2)
2
>>> standard_arg(arg=2)
2
µÚ¶þ¸öº¯Êý?pos_only_arg ?µÄº¯Êý¶¨ÒåÖÐÓÐ?/ ,½öÏÞʹÓÃλÖÃÐβÎ:
>>>
>>> pos_only_arg(1)
1
>>> pos_only_arg(arg=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'
µÚÈý¸öº¯Êý?kwd_only_args ?µÄº¯Êý¶¨Òåͨ¹ý?* ?±íÃ÷½öÏ޹ؼü×Ö²ÎÊý:
>>>
>>> kwd_only_arg(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given
>>> kwd_only_arg(arg=3)
3
×îºóÒ»¸öº¯ÊýÔÚͬһ¸öº¯Êý¶¨ÒåÖÐ,ʹÓÃÁËÈ«²¿ÈýÖÖµ÷ÓùßÀý:
>>>
>>> combined_example(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given
>>> combined_example(1, 2, kwd_only=3)
1 2 3
>>> combined_example(1, standard=2, kwd_only=3)
1 2 3
>>> combined_example(pos_only=1, standard=2, kwd_only=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'
ÏÂÃæµÄº¯Êý¶¨ÒåÖÐ,kwds ?°Ñ?name ?µ±×÷¼ü,Òò´Ë,¿ÉÄÜÓëλÖòÎÊý?name ?²úÉúDZÔÚ³åÍ»:
def foo(name, **kwds):
return 'name' in kwds
µ÷Óøú¯Êý²»¿ÉÄÜ·µ»Ø?True ,ÒòΪ¹Ø¼ü×Ö?'name' ?×ÜÓëµÚÒ»¸öÐβΰ󶨡£ÀýÈç:
>>>
>>> foo(1, **{'name': 2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'
>>>
¼ÓÉÏ?/ ?(½öÏÞλÖòÎÊý)ºó,¾Í¿ÉÒÔÁË¡£´Ëʱ,º¯Êý¶¨Òå°Ñ?name ?µ±×÷λÖòÎÊý,'name' ?Ò²¿ÉÒÔ×÷Ϊ¹Ø¼ü×Ö²ÎÊýµÄ¼ü:
def foo(name, /, **kwds):
return 'name' in kwds
>>> foo(1, **{'name': 2})
True
»»¾ä»°Ëµ,½öÏÞλÖÃÐβεÄÃû³Æ¿ÉÒÔÔÚ?**kwds ?ÖÐʹÓÃ,¶ø²»²úÉúÆçÒå¡£
4.8.3.5.?С½á
ÒÔÏÂÓÃÀý¾ö¶¨ÄÄЩÐβοÉÒÔÓÃÓÚº¯Êý¶¨Òå:
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
˵Ã÷:
-
ʹÓýöÏÞλÖÃÐβÎ,¿ÉÒÔÈÃÓû§ÎÞ·¨Ê¹ÓÃÐβÎÃû¡£ÐβÎÃûûÓÐʵ¼ÊÒâÒåʱ,Ç¿ÖƵ÷Óú¯ÊýµÄʵ²Î˳Ðòʱ,»òͬʱ½ÓÊÕλÖÃÐβκ͹ؼü×Öʱ,ÕâÖÖ·½Ê½ºÜÓÐÓᣠ-
µ±ÐβÎÃûÓÐʵ¼ÊÒâÒå,ÇÒÏÔʽÃû³Æ¿ÉÒÔÈú¯Êý¶¨Òå¸üÒ×Àí½âʱ,×èÖ¹Óû§ÒÀÀµ´«µÝʵ²ÎµÄλÖÃʱ,²ÅʹÓùؼü×Ö¡£ -
¶ÔÓÚ API,ʹÓýöÏÞλÖÃÐβÎ,¿ÉÒÔ·ÀֹδÀ´ÐÞ¸ÄÐβÎÃûʱÔì³ÉÆÆ»µÐ﵀ API ±ä¶¯¡£
4.8.4.?ÈÎÒâʵ²ÎÁбí
µ÷Óú¯Êýʱ,ʹÓÃÈÎÒâÊýÁ¿µÄʵ²ÎÊÇ×îÉÙ¼ûµÄÑ¡Ïî¡£ÕâЩʵ²Î°üº¬ÔÚÔª×éÖÐ(Ïê¼û?Ôª×éºÍÐòÁÐ?)¡£ÔڿɱäÊýÁ¿µÄʵ²Î֮ǰ,¿ÉÄÜÓÐÈô¸É¸öÆÕͨ²ÎÊý:
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
variadic?²ÎÊýÓÃÓڲɼ¯´«µÝ¸øº¯ÊýµÄËùÓÐÊ£Óà²ÎÊý,Òò´Ë,ËüÃÇͨ³£ÔÚÐβÎÁбíµÄĩβ¡£*args ?ÐβκóµÄÈκÎÐÎʽ²ÎÊýÖ»ÄÜÊǽöÏ޹ؼü×Ö²ÎÊý,¼´Ö»ÄÜÓÃ×÷¹Ø¼ü×Ö²ÎÊý,²»ÄÜÓÃ×÷λÖòÎÊý:
>>>
>>> def concat(*args, sep="/"):
... return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
4.8.5.?½â°üʵ²ÎÁбí
º¯Êýµ÷ÓÃÒªÇó¶ÀÁ¢µÄλÖòÎÊý,µ«Êµ²ÎÔÚÁбí»òÔª×éÀïʱ,ÒªÖ´ÐÐÏà·´µÄ²Ù×÷¡£ÀýÈç,ÄÚÖõÄ?range()?º¯ÊýÒªÇó¶ÀÁ¢µÄ?start?ºÍ?stop?ʵ²Î¡£Èç¹ûÕâЩ²ÎÊý²»ÊǶÀÁ¢µÄ,ÔòÒªÔÚµ÷Óú¯Êýʱ,ÓÃ?* ?²Ù×÷·û°Ñʵ²Î´ÓÁбí»òÔª×é½â°ü³öÀ´:
>>>
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
ͬÑù,×Öµä¿ÉÒÔÓÃ?** ?²Ù×÷·û´«µÝ¹Ø¼ü×Ö²ÎÊý:
>>>
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
4.8.6.?Lambda ±í´ïʽ
lambda?¹Ø¼ü×ÖÓÃÓÚ´´½¨Ð¡ÇɵÄÄäÃûº¯Êý¡£lambda?a,?b:?a+b ?º¯Êý·µ»ØÁ½¸ö²ÎÊýµÄºÍ¡£Lambda º¯Êý¿ÉÓÃÓÚÈκÎÐèÒªº¯Êý¶ÔÏóµÄµØ·½¡£ÔÚÓï·¨ÉÏ,ÄäÃûº¯ÊýÖ»ÄÜÊǵ¥¸ö±í´ïʽ¡£ÔÚÓïÒåÉÏ,ËüÖ»Êdz£¹æº¯Êý¶¨ÒåµÄÓï·¨ÌÇ¡£ÓëǶÌ׺¯Êý¶¨ÒåÒ»Ñù,lambda º¯Êý¿ÉÒÔÒýÓðüº¬×÷ÓÃÓòÖеıäÁ¿:
>>>
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
ÉÏÀýÓà lambda ±í´ïʽ·µ»Øº¯Êý¡£»¹¿ÉÒÔ°ÑÄäÃûº¯ÊýÓÃ×÷´«µÝµÄʵ²Î:
>>>
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
4.8.7.?Îĵµ×Ö·û´®
ÒÔÏÂÊÇÎĵµ×Ö·û´®ÄÚÈݺ͸ñʽµÄÔ¼¶¨¡£
µÚÒ»ÐÐӦΪ¶ÔÏóÓÃ;µÄ¼ò¶ÌÕªÒª¡£Îª±£³Ö¼ò½à,²»ÒªÔÚÕâÀïÏÔʽ˵Ã÷¶ÔÏóÃû»òÀàÐÍ,ÒòΪ¿Éͨ¹ýÆäËû·½Ê½»ñÈ¡ÕâЩÐÅÏ¢(³ý·Ç¸ÃÃû³ÆÅöÇÉÊÇÃèÊöº¯Êý²Ù×÷µÄ¶¯´Ê)¡£ÕâÒ»ÐÐÓ¦ÒÔ´óд×Öĸ¿ªÍ·,ÒÔ¾äµã½áβ¡£
Îĵµ×Ö·û´®Îª¶àÐÐʱ,µÚ¶þÐÐӦΪ¿Õ°×ÐÐ,ÔÚÊÓ¾õÉϽ«ÕªÒªÓëÆäÓàÃèÊö·Ö¿ª¡£ºóÃæµÄÐпɰüº¬Èô¸É¶ÎÂä,ÃèÊö¶ÔÏóµÄµ÷ÓÃÔ¼¶¨¡¢¸±×÷Óõȡ£
Python ½âÎöÆ÷²»»áɾ³ý Python ÖжàÐÐ×Ö·û´®×ÖÃæÖµµÄËõ½ø,Òò´Ë,Îĵµ´¦Àí¹¤¾ßÓ¦ÔÚ±ØҪʱɾ³ýËõ½ø¡£ÕâÏî²Ù×÷×ñÑÒÔÏÂÔ¼¶¨:Îĵµ×Ö·û´®µÚÒ»ÐÐ?Ö®ºó?µÄµÚÒ»¸ö·Ç¿ÕÐоö¶¨ÁËÕû¸öÎĵµ×Ö·û´®µÄËõ½øÁ¿(µÚÒ»ÐÐͨ³£Óë×Ö·û´®¿ªÍ·µÄÒýºÅÏàÁÚ,ÆäËõ½øÔÚ×Ö·û´®Öв¢²»Ã÷ÏÔ,Òò´Ë,²»ÄÜÓõÚÒ»ÐеÄËõ½ø),È»ºó,ɾ³ý×Ö·û´®ÖÐËùÓÐÐпªÍ·´¦Óë´ËËõ½ø¡°µÈ¼Û¡±µÄ¿Õ°×·û¡£²»ÄÜÓбȴËËõ½ø¸üÉÙµÄÐÐ,µ«Èç¹û³öÏÖÁËËõ½ø¸üÉÙµÄÐÐ,Ӧɾ³ýÕâЩÐеÄËùÓÐÇ°µ¼¿Õ°×·û¡£×ª»¯ÖƱí·ûºó(ͨ³£Îª 8 ¸ö¿Õ¸ñ),Ó¦²âÊÔ¿Õ°×·ûµÄµÈЧÐÔ¡£
ÏÂÃæÊǶàÐÐÎĵµ×Ö·û´®µÄÒ»¸öÀý×Ó:
>>>
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
4.8.8.?º¯Êý×¢½â
º¯Êý×¢½â?ÊÇ¿ÉÑ¡µÄÓû§×Ô¶¨Ò庯ÊýÀàÐ͵ÄÔªÊý¾ÝÍêÕûÐÅÏ¢(Ïê¼û?PEP 3107?ºÍ?PEP 484?)¡£
±ê×¢?ÒÔ×ÖµäµÄÐÎʽ´æ·ÅÔÚº¯ÊýµÄ?__annotations__ ?ÊôÐÔÖÐ,²¢ÇÒ²»»áÓ°Ï캯ÊýµÄÈκÎÆäËû²¿·Ö¡£ Ðβαê×¢µÄ¶¨Ò巽ʽÊÇÔÚÐβÎÃûºó¼ÓðºÅ,ºóÃæ¸úÒ»¸ö±í´ïʽ,¸Ã±í´ïʽ»á±»ÇóֵΪ±ê×¢µÄÖµ¡£ ·µ»ØÖµ±ê×¢µÄ¶¨Ò巽ʽÊǼÓ×éºÏ·ûºÅ?-> ,ºóÃæ¸úÒ»¸ö±í´ïʽ,¸Ã±êעλÓÚÐβÎÁбíºÍ±íʾ?def?Óï¾ä½áÊøµÄðºÅÖ®¼ä¡£ ÏÂÃæµÄʾÀýÓÐÒ»¸ö±ØÐëµÄ²ÎÊý,Ò»¸ö¿ÉÑ¡µÄ¹Ø¼ü×Ö²ÎÊýÒÔ¼°·µ»ØÖµ¶¼´øÓÐÏàÓ¦µÄ±ê×¢:
>>>
>>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'
5.?Êý¾Ý½á¹¹
±¾ÕÂÉîÈë½²½â֮ǰѧ¹ýµÄһЩÄÚÈÝ,ͬʱ,»¹Ôö¼ÓÁËеÄ֪ʶµã¡£
5.1.?ÁбíÏê½â
ÁбíÊý¾ÝÀàÐÍÖ§³ÖºÜ¶à·½·¨,Áбí¶ÔÏóµÄËùÓз½·¨ËùʾÈçÏÂ:
list.append(x)
ÔÚÁбíĩβÌí¼ÓÒ»¸öÔªËØ,Ï൱ÓÚ?a[len(a):]?=?[x] ?¡£
list.extend(iterable)
Óÿɵü´ú¶ÔÏóµÄÔªËØÀ©Õ¹ÁÐ±í¡£Ï൱ÓÚ?a[len(a):]?=?iterable ?¡£
list.insert(i,?x)
ÔÚÖ¸¶¨Î»ÖòåÈëÔªËØ¡£µÚÒ»¸ö²ÎÊýÊDzåÈëÔªËصÄË÷Òý,Òò´Ë,a.insert(0,?x) ?ÔÚÁÐ±í¿ªÍ·²åÈëÔªËØ,?a.insert(len(a),?x) ?µÈͬÓÚ?a.append(x) ?¡£
list.remove(x)
´ÓÁбíÖÐɾ³ýµÚÒ»¸öֵΪ?x?µÄÔªËØ¡£Î´ÕÒµ½Ö¸¶¨ÔªËØʱ,´¥·¢?ValueError?Òì³£¡£
list.pop([i])
ɾ³ýÁбíÖÐÖ¸¶¨Î»ÖõÄÔªËØ,²¢·µ»Ø±»É¾³ýµÄÔªËØ¡£Î´Ö¸¶¨Î»ÖÃʱ,a.pop() ?ɾ³ý²¢·µ»ØÁбíµÄ×îºóÒ»¸öÔªËØ¡£(·½·¨Ç©ÃûÖÐ?i?Á½±ßµÄ·½À¨ºÅ±íʾ¸Ã²ÎÊýÊÇ¿ÉÑ¡µÄ,²»ÊÇÒªÇóÊäÈë·½À¨ºÅ¡£ÕâÖÖ±íʾ·¨³£¼ûÓÚ Python ²Î¿¼¿â)¡£
list.clear()
ɾ³ýÁбíÀïµÄËùÓÐÔªËØ,Ï൱ÓÚ?del?a[:] ?¡£
list.index(x[,?start[,?end]])
·µ»ØÁбíÖеÚÒ»¸öֵΪ?x?µÄÔªËصÄÁã»ùË÷Òý¡£Î´ÕÒµ½Ö¸¶¨ÔªËØʱ,´¥·¢?ValueError?Òì³£¡£
¿ÉÑ¡²ÎÊý?start?ºÍ?end?ÊÇÇÐƬ·ûºÅ,ÓÃÓÚ½«ËÑË÷ÏÞÖÆΪÁбíµÄÌض¨×ÓÐòÁС£·µ»ØµÄË÷ÒýÊÇÏà¶ÔÓÚÕû¸öÐòÁеĿªÊ¼¼ÆËãµÄ,¶ø²»ÊÇ?start?²ÎÊý¡£
list.count(x)
·µ»ØÁбíÖÐÔªËØ?x?³öÏֵĴÎÊý¡£
list.sort(*,?key=None,?reverse=False)
¾ÍµØÅÅÐòÁбíÖеÄÔªËØ(ÒªÁ˽â×Ô¶¨ÒåÅÅÐò²ÎÊý,Ïê¼û?sorted())¡£
list.reverse()
·×ªÁбíÖеÄÔªËØ¡£
list.copy()
·µ»ØÁбíµÄdz¿½±´¡£Ï൱ÓÚ?a[:] ?¡£
¶àÊýÁÐ±í·½·¨Ê¾Àý:
>>>
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
insert ¡¢remove ¡¢sort ?µÈ·½·¨Ö»ÐÞ¸ÄÁбí,²»Êä³ö·µ»ØÖµ¡ª¡ª·µ»ØµÄĬÈÏֵΪ?None ?¡£1?ÕâÊÇËùÓÐ Python ¿É±äÊý¾Ý½á¹¹µÄÉè¼ÆÔÔò¡£
»¹ÓÐ,²»ÊÇËùÓÐÊý¾Ý¶¼¿ÉÒÔÅÅÐò»ò±È½Ï¡£ÀýÈç,[None,?'hello',?10] ?¾Í²»¿ÉÅÅÐò,ÒòΪÕûÊý²»ÄÜÓë×Ö·û´®¶Ô±È,¶ø?None?²»ÄÜÓëÆäËûÀàÐͶԱȡ£ÓÐЩÀàÐ͸ù±¾¾ÍûÓж¨Òå˳Ðò¹Øϵ,ÀýÈç,3+4j?<?5+7j ?ÕâÖֶԱȲÙ×÷¾ÍÊÇÎÞЧµÄ¡£
5.1.1.?ÓÃÁбíʵÏÖ¶ÑÕ»
ʹÓÃÁÐ±í·½·¨ÊµÏÖ¶ÑÕ»·Ç³£ÈÝÒ×,×îºó²åÈëµÄ×îÏÈÈ¡³ö(¡°ºó½øÏȳö¡±)¡£°ÑÔªËØÌí¼Óµ½¶ÑÕ»µÄ¶¥¶Ë,ʹÓÃ?append() ?¡£´Ó¶ÑÕ»¶¥²¿È¡³öÔªËØ,ʹÓÃ?pop() ?,²»ÓÃÖ¸¶¨Ë÷Òý¡£ÀýÈç:
>>>
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
5.1.2.?ÓÃÁбíʵÏÖ¶ÓÁÐ
ÁбíÒ²¿ÉÒÔÓÃ×÷¶ÓÁÐ,×îÏȼÓÈëµÄÔªËØ,×îÏÈÈ¡³ö(¡°ÏȽøÏȳö¡±);È»¶ø,Áбí×÷Ϊ¶ÓÁеÄЧÂʺܵ͡£ÒòΪ,ÔÚÁбíĩβÌí¼ÓºÍɾ³ýÔªËطdz£¿ì,µ«ÔÚÁÐ±í¿ªÍ·²åÈë»òÒƳýÔªËØÈ´ºÜÂý(ÒòΪËùÓÐÆäËûÔªËض¼±ØÐëÒƶ¯Ò»Î»)¡£
ʵÏÖ¶ÓÁÐ×îºÃÓÃ?collections.deque,¿ÉÒÔ¿ìËÙ´ÓÁ½¶ËÌí¼Ó»òɾ³ýÔªËØ¡£ÀýÈç:
>>>
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
5.1.3.?ÁбíÍƵ¼Ê½
ÁбíÍƵ¼Ê½´´½¨ÁбíµÄ·½Ê½¸ü¼ò½à¡£³£¼ûµÄÓ÷¨Îª,¶ÔÐòÁлò¿Éµü´ú¶ÔÏóÖеÄÿ¸öÔªËØÓ¦ÓÃijÖÖ²Ù×÷,ÓÃÉú³ÉµÄ½á¹û´´½¨ÐµÄÁбí;»òÓÃÂú×ãÌض¨Ìõ¼þµÄÔªËØ´´½¨×ÓÐòÁС£
ÀýÈç,´´½¨Æ½·½ÖµµÄÁбí:
>>>
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
×¢Òâ,Õâ¶Î´úÂë´´½¨(»ò¸²¸Ç)±äÁ¿?x ,¸Ã±äÁ¿ÔÚÑ»·½áÊøºóÈÔÈ»´æÔÚ¡£ÏÂÊö·½·¨¿ÉÒÔÎÞ¸±×÷ÓõؼÆËãƽ·½Áбí:
squares = list(map(lambda x: x**2, range(10)))
»òµÈ¼ÛÓÚ:
squares = [x**2 for x in range(10)]
ÉÏÃæÕâÖÖд·¨¸ü¼ò½à¡¢Ò׶Á¡£
ÁбíÍƵ¼Ê½µÄ·½À¨ºÅÄÚ°üº¬ÒÔÏÂÄÚÈÝ:Ò»¸ö±í´ïʽ,ºóÃæΪһ¸ö?for ?×Ó¾ä,È»ºó,ÊÇÁã¸ö»ò¶à¸ö?for ?»ò?if ?×Ӿ䡣½á¹ûÊÇÓɱí´ïʽÒÀ¾Ý?for ?ºÍ?if ?×Ó¾äÇóÖµ¼ÆËã¶øµÃ³öÒ»¸öÐÂÁÐ±í¡£ ¾ÙÀýÀ´Ëµ,ÒÔÏÂÁбíÍƵ¼Ê½½«Á½¸öÁбíÖв»ÏàµÈµÄÔªËØ×éºÏÆðÀ´:
>>>
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
µÈ¼ÛÓÚ:
>>>
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
×¢Òâ,ÉÏÃæÁ½¶Î´úÂëÖÐ,for?ºÍ?if?µÄ˳ÐòÏàͬ¡£
±í´ïʽÊÇÔª×é(ÀýÈçÉÏÀýµÄ?(x,?y) )ʱ,±ØÐë¼ÓÉÏÀ¨ºÅ:
>>>
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in <module>
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
ÁбíÍƵ¼Ê½¿ÉÒÔʹÓø´Ôӵıí´ïʽºÍǶÌ׺¯Êý:
>>>
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
5.1.4.?ǶÌ×µÄÁбíÍƵ¼Ê½
ÁбíÍƵ¼Ê½Öеijõʼ±í´ïʽ¿ÉÒÔÊÇÈκαí´ïʽ,ÉõÖÁ¿ÉÒÔÊÇÁíÒ»¸öÁбíÍƵ¼Ê½¡£
ÏÂÃæÕâ¸ö 3x4 ¾ØÕó,ÓÉ 3 ¸ö³¤¶ÈΪ 4 µÄÁбí×é³É:
>>>
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
ÏÂÃæµÄÁбíÍƵ¼Ê½¿ÉÒÔתÖÃÐÐÁÐ:
>>>
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
As we saw in the previous section, the inner list comprehension is evaluated in the context of the?for?that follows it, so this example is equivalent to:
>>>
>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
·´¹ýÀ´Ëµ,Ò²µÈ¼ÛÓÚ:
>>>
>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
ʵ¼ÊÓ¦ÓÃÖÐ,×îºÃÓÃÄÚÖú¯ÊýÌæ´ú¸´ÔÓµÄÁ÷³ÌÓï¾ä¡£´Ëʱ,zip()?º¯Êý¸üºÃÓÃ:
>>>
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
¹ØÓÚ±¾ÐÐÖÐÐǺŵÄÏêϸ˵Ã÷,²Î¼û?½â°üʵ²ÎÁÐ±í¡£
5.2.?del ?Óï¾ä
del?Óï¾ä°´Ë÷Òý,¶ø²»ÊÇÖµ´ÓÁбíÖÐÒƳýÔªËØ¡£Óë·µ»ØÖµµÄ?pop() ?·½·¨²»Í¬,?del ?Óï¾äÒ²¿ÉÒÔ´ÓÁбíÖÐÒƳýÇÐƬ,»òÇå¿ÕÕû¸öÁбí(֮ǰÊǽ«¿ÕÁÐ±í¸³Öµ¸øÇÐƬ)¡£ ÀýÈç:
>>>
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
del?Ò²¿ÉÒÔÓÃÀ´É¾³ýÕû¸ö±äÁ¿:
>>>
>>> del a
´Ëºó,ÔÙÒýÓÃ?a ?¾Í»á±¨´í(Ö±µ½ÎªËü¸³ÓëÁíÒ»¸öÖµ)¡£ºóÎÄ»á½éÉÜ?del?µÄÆäËûÓ÷¨¡£
5.3.?Ôª×éºÍÐòÁÐ
ÁбíºÍ×Ö·û´®Óкܶ๲ÐÔ,ÀýÈç,Ë÷ÒýºÍÇÐƬ²Ù×÷¡£ÕâÁ½ÖÖÊý¾ÝÀàÐÍÊÇ?ÐòÁÐ?(²Î¼û?ÐòÁÐÀàÐÍ --- list, tuple, range)¡£Ëæ×Å Python ÓïÑԵķ¢Õ¹,ÆäËûµÄÐòÁÐÀàÐÍÒ²±»¼ÓÈëÆäÖС£±¾½Ú½éÉÜÁíÒ»ÖÖ±ê×¼ÐòÁÐÀàÐÍ:Ôª×é¡£
Ôª×éÓɶà¸öÓöººÅ¸ô¿ªµÄÖµ×é³É,ÀýÈç:
>>>
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
Êä³öʱ,Ôª×鶼ҪÓÉÔ²À¨ºÅ±ê×¢,ÕâÑù²ÅÄÜÕýÈ·µØ½âÊÍǶÌ×Ôª×é¡£ÊäÈëʱ,Ô²À¨ºÅ¿ÉÓпÉÎÞ,²»¹ý¾³£ÊDZØÐëµÄ(Èç¹ûÔª×éÊǸü´óµÄ±í´ïʽµÄÒ»²¿·Ö)¡£²»ÔÊÐíΪԪ×éÖеĵ¥¸öÔªËظ³Öµ,µ±È»,¿ÉÒÔ´´½¨º¬ÁбíµÈ¿É±ä¶ÔÏóµÄÔª×é¡£
ËäÈ»,Ôª×éÓëÁбíºÜÏñ,µ«Ê¹Óó¡¾°²»Í¬,ÓÃ;Ҳ²»Í¬¡£Ôª×éÊÇ?immutable?(²»¿É±äµÄ),Ò»°ã¿É°üº¬ÒìÖÊÔªËØÐòÁÐ,ͨ¹ý½â°ü(¼û±¾½ÚÏÂÎÄ)»òË÷Òý·ÃÎÊ(Èç¹ûÊÇ?namedtuples,¿ÉÒÔÊôÐÔ·ÃÎÊ)¡£ÁбíÊÇ?mutable?(¿É±äµÄ),ÁбíÔªËØÒ»°ãΪͬÖÊÀàÐÍ,¿Éµü´ú·ÃÎÊ¡£
¹¹Ôì 0 ¸ö»ò 1 ¸öÔªËصÄÔª×é±È½ÏÌØÊâ:ΪÁËÊÊÓ¦ÕâÖÖÇé¿ö,¶Ô¾ä·¨ÓÐһЩ¶îÍâµÄ¸Ä±ä¡£ÓÃÒ»¶Ô¿ÕÔ²À¨ºÅ¾Í¿ÉÒÔ´´½¨¿ÕÔª×é;Ö»ÓÐÒ»¸öÔªËصÄÔª×é¿ÉÒÔͨ¹ýÔÚÕâ¸öÔªËغóÌí¼Ó¶ººÅÀ´¹¹½¨(Ô²À¨ºÅÀïÖ»ÓÐÒ»¸öÖµµÄ»°²»¹»Ã÷È·)¡£³óª,µ«ÊÇÓÐЧ¡£ÀýÈç:
>>>
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Óï¾ä?t?=?12345,?54321,?'hello!' ?ÊÇ?Ôª×é´ò°ü?µÄÀý×Ó:Öµ?12345 ,?54321 ?ºÍ?'hello!' ?Ò»Æð±»´ò°ü½øÔª×é¡£Äæ²Ù×÷Ò²¿ÉÒÔ:
>>>
>>> x, y, z = t
³Æ֮Ϊ?ÐòÁнâ°ü?Ò²ÊÇÍ×Í×µÄ,ÊÊÓÃÓÚÓÒ²àµÄÈκÎÐòÁС£ÐòÁнâ°üʱ,×ó²à±äÁ¿ÓëÓÒ²àÐòÁÐÔªËصÄÊýÁ¿Ó¦ÏàµÈ¡£×¢Òâ,¶àÖظ³ÖµÆäʵֻÊÇÔª×é´ò°üºÍÐòÁнâ°üµÄ×éºÏ¡£
5.4.?¼¯ºÏ
Python »¹Ö§³Ö?¼¯ºÏ?ÕâÖÖÊý¾ÝÀàÐÍ¡£¼¯ºÏÊÇÓɲ»Öظ´ÔªËØ×é³ÉµÄÎÞÐòÈÝÆ÷¡£»ù±¾Ó÷¨°üÀ¨³ÉÔ±¼ì²â¡¢Ïû³ýÖظ´ÔªËØ¡£¼¯ºÏ¶ÔÏóÖ§³ÖºÏ¼¯¡¢½»¼¯¡¢²î¼¯¡¢¶Ô³Æ²î·ÖµÈÊýѧÔËËã¡£
´´½¨¼¯ºÏÓû¨À¨ºÅ»ò?set()?º¯Êý¡£×¢Òâ,´´½¨¿Õ¼¯ºÏÖ»ÄÜÓÃ?set() ,²»ÄÜÓÃ?{} ,{} ?´´½¨µÄÊÇ¿Õ×Öµä,ÏÂһС½Ú½éÉÜÊý¾Ý½á¹¹:×ֵ䡣
ÒÔÏÂÊÇһЩ¼òµ¥µÄʾÀý
>>>
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Óë?ÁбíÍƵ¼Ê½?ÀàËÆ,¼¯ºÏÒ²Ö§³ÖÍƵ¼Ê½:
>>>
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
5.5.?×Öµä
×Öµä?(²Î¼û?Ó³ÉäÀàÐÍ --- dict) Ò²ÊÇÒ»ÖÖ³£ÓÃµÄ Python ƒÈÖÃÊý¾ÝÀàÐÍ¡£ÆäËûÓïÑÔ¿ÉÄÜ°Ñ×Öµä³ÆΪ?ÁªºÏÄÚ´æ?»ò?ÁªºÏÊý×é¡£ÓëÒÔÁ¬ÐøÕûÊýΪË÷ÒýµÄÐòÁв»Í¬,×ÖµäÒÔ?¹Ø¼ü×Ö?ΪË÷Òý,¹Ø¼ü×Öͨ³£ÊÇ×Ö·û´®»òÊý×Ö,Ò²¿ÉÒÔÊÇÆäËûÈÎÒâ²»¿É±äÀàÐÍ¡£Ö»°üº¬×Ö·û´®¡¢Êý×Ö¡¢Ôª×éµÄÔª×é,Ò²¿ÉÒÔÓÃ×÷¹Ø¼ü×Ö¡£µ«Èç¹ûÔª×éÖ±½Ó»ò¼ä½ÓµØ°üº¬Á˿ɱä¶ÔÏó,¾Í²»ÄÜÓÃ×÷¹Ø¼ü×Ö¡£ÁÐ±í²»Äܵ±¹Ø¼ü×Ö,ÒòΪÁбí¿ÉÒÔÓÃË÷Òý¡¢ÇÐƬ¡¢append() ?¡¢extend() ?µÈ·½·¨Ð޸ġ£
¿ÉÒÔ°Ñ×ÖµäÀí½âΪ?¼üÖµ¶Ô?µÄ¼¯ºÏ,µ«×ÖµäµÄ¼ü±ØÐëÊÇΨһµÄ¡£»¨À¨ºÅ?{} ?ÓÃÓÚ´´½¨¿Õ×ֵ䡣ÁíÒ»ÖÖ³õʼ»¯×ÖµäµÄ·½Ê½ÊÇ,ÔÚ»¨À¨ºÅÀïÊäÈ붺ºÅ·Ö¸ôµÄ¼üÖµ¶Ô,ÕâÒ²ÊÇ×ÖµäµÄÊä³ö·½Ê½¡£
×ÖµäµÄÖ÷ÒªÓÃ;ÊÇͨ¹ý¹Ø¼ü×Ö´æ´¢¡¢ÌáÈ¡Öµ¡£ÓÃ?del ?¿ÉÒÔɾ³ý¼üÖµ¶Ô¡£ÓÃÒÑ´æÔڵĹؼü×Ö´æ´¢Öµ,Óë¸Ã¹Ø¼ü×Ö¹ØÁªµÄ¾ÉÖµ»á±»È¡´ú¡£Í¨¹ý²»´æÔڵļüÌáÈ¡Öµ,Ôò»á±¨´í¡£
¶Ô×ÖµäÖ´ÐÐ?list(d) ?²Ù×÷,·µ»Ø¸Ã×ÖµäÖÐËùÓмüµÄÁбí,°´²åÈë´ÎÐòÅÅÁÐ(ÈçÐèÅÅÐò,ÇëʹÓÃ?sorted(d) )¡£¼ì²é×ÖµäÀïÊÇ·ñ´æÔÚij¸ö¼ü,ʹÓùؼü×Ö?in¡£
ÒÔÏÂÊÇһЩ×ÖµäµÄ¼òµ¥Ê¾Àý:
>>>
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
dict()?¹¹Ô캯Êý¿ÉÒÔÖ±½ÓÓüüÖµ¶ÔÐòÁд´½¨×Öµä:
>>>
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
×ÖµäÍƵ¼Ê½¿ÉÒÔÓÃÈÎÒâ¼üÖµ±í´ïʽ´´½¨×Öµä:
>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
¹Ø¼ü×ÖÊDZȽϼòµ¥µÄ×Ö·û´®Ê±,Ö±½ÓÓùؼü×Ö²ÎÊýÖ¸¶¨¼üÖµ¶Ô¸ü±ã½Ý:
>>>
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
5.6.?Ñ»·µÄ¼¼ÇÉ
ÔÚ×ÖµäÖÐÑ»·Ê±,ÓÃ?items() ?·½·¨¿Éͬʱȡ³ö¼üºÍ¶ÔÓ¦µÄÖµ:
>>>
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
ÔÚÐòÁÐÖÐÑ»·Ê±,ÓÃ?enumerate()?º¯Êý¿ÉÒÔͬʱȡ³öλÖÃË÷ÒýºÍ¶ÔÓ¦µÄÖµ:
>>>
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
ͬʱѻ·Á½¸ö»ò¶à¸öÐòÁÐʱ,ÓÃ?zip()?º¯Êý¿ÉÒÔ½«ÆäÄÚµÄÔªËØһһƥÅä:
>>>
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
ÄæÏòÑ»·ÐòÁÐʱ,ÏÈÕýÏò¶¨Î»ÐòÁÐ,È»ºóµ÷ÓÃ?reversed()?º¯Êý:
>>>
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
°´Ö¸¶¨Ë³ÐòÑ»·ÐòÁÐ,¿ÉÒÔÓÃ?sorted()?º¯Êý,ÔÚ²»¸Ä¶¯ÔÐòÁеĻù´¡ÉÏ,·µ»ØÒ»¸öÖØеÄÐòÁÐ:
>>>
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
... print(i)
...
apple
apple
banana
orange
orange
pear
ʹÓÃ?set()?È¥³ýÐòÁÐÖеÄÖظ´ÔªËØ¡£Ê¹ÓÃ?sorted()?¼Ó?set()?Ôò°´ÅÅÐòºóµÄ˳Ðò,Ñ»·±éÀúÐòÁÐÖеÄΨһԪËØ:
>>>
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
Ò»°ãÀ´Ëµ,ÔÚÑ»·ÖÐÐÞ¸ÄÁбíµÄÄÚÈÝʱ,´´½¨ÐÂÁбí±È½Ï¼òµ¥,ÇÒ°²È«:
>>>
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
... if not math.isnan(value):
... filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]
5.7.?ÉîÈëÌõ¼þ¿ØÖÆ
while ?ºÍ?if ?Ìõ¼þ¾ä²»Ö»¿ÉÒÔ½øÐбȽÏ,»¹¿ÉÒÔʹÓÃÈÎÒâÔËËã·û¡£
±È½ÏÔËËã·û?in ?ºÍ?not?in ?ÓÃÓÚÖ´ÐÐÈ·¶¨Ò»¸öÖµÊÇ·ñ´æÔÚ(»ò²»´æÔÚ)ÓÚij¸öÈÝÆ÷ÖеijÉÔ±¼ì²â¡£ ÔËËã·û?is ?ºÍ?is?not ?ÓÃÓڱȽÏÁ½¸ö¶ÔÏóÊÇ·ñÊÇͬһ¸ö¶ÔÏó¡£ ËùÓбȽÏÔËËã·ûµÄÓÅÏȼ¶¶¼Ò»Ñù,ÇÒµÍÓÚÈκÎÊýÖµÔËËã·û¡£
±È½Ï²Ù×÷Ö§³ÖÁ´Ê½²Ù×÷¡£ÀýÈç,a?<?b?==?c ?УÑé?a ?ÊÇ·ñСÓÚ?b ,ÇÒ?b ?ÊÇ·ñµÈÓÚ?c ¡£
±È½Ï²Ù×÷¿ÉÒÔÓò¼¶ûÔËËã·û?and ?ºÍ?or ?×éºÏ,²¢ÇÒ,±È½Ï²Ù×÷(»òÆäËû²¼¶ûÔËËã)µÄ½á¹û¶¼¿ÉÒÔÓÃ?not ?È¡·´¡£ÕâЩ²Ù×÷·ûµÄÓÅÏȼ¶µÍÓڱȽϲÙ×÷·û;not ?µÄÓÅÏȼ¶×î¸ß,?or ?µÄÓÅÏȼ¶×îµÍ,Òò´Ë,A?and?not?B?or?C ?µÈ¼ÛÓÚ?(A?and?(not?B))?or?C ¡£ÓëÆäËûÔËËã·û²Ù×÷Ò»Ñù,´Ë´¦Ò²¿ÉÒÔÓÃÔ²À¨ºÅ±íʾÏëÒªµÄ×éºÏ¡£
²¼¶ûÔËËã·û?and ?ºÍ?or ?Ò²³ÆΪ?¶Ì·?ÔËËã·û:Æä²ÎÊý´Ó×óÖÁÓÒ½âÎö,Ò»µ©¿ÉÒÔÈ·¶¨½á¹û,½âÎö¾Í»áÍ£Ö¹¡£ÀýÈç,Èç¹û?A ?ºÍ?C ?ΪÕæ,B ?Ϊ¼Ù,ÄÇô?A?and?B?and?C ?²»»á½âÎö?C ¡£ÓÃ×÷ÆÕֵͨ¶ø²»ÊDz¼¶ûֵʱ,¶Ì·²Ù×÷·û·µ»ØµÄֵͨ³£ÊÇ×îºóÒ»¸ö±äÁ¿¡£
»¹¿ÉÒ԰ѱȽϲÙ×÷»òÂß¼±í´ïʽµÄ½á¹û¸³Öµ¸ø±äÁ¿,ÀýÈç:
>>>
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
×¢Òâ,Python Óë C ²»Í¬,ÔÚ±í´ïʽÄÚ²¿¸³Öµ±ØÐëÏÔʽʹÓÃ?º£ÏóÔËËã·û?:= ¡£ Õâ±ÜÃâÁË C ³ÌÐòÖг£¼ûµÄÎÊÌâ:ÒªÔÚ±í´ïʽÖÐд?== ?ʱ,ȴд³ÉÁË?= ¡£
5.8.?ÐòÁкÍÆäËûÀàÐ͵ıȽÏ
ÐòÁжÔÏó¿ÉÒÔÓëÏàͬÐòÁÐÀàÐ͵ÄÆäËû¶ÔÏó±È½Ï¡£ÕâÖֱȽÏʹÓÃ?×Öµäʽ?˳Ðò:Ê×ÏÈ,±È½ÏÇ°Á½¸ö¶ÔÓ¦ÔªËØ,Èç¹û²»ÏàµÈ,Ôò¿ÉÈ·¶¨±È½Ï½á¹û;Èç¹ûÏàµÈ,Ôò±È½ÏÖ®ºóµÄÁ½¸öÔªËØ,ÒÔ´ËÀàÍÆ,Ö±µ½ÆäÖÐÒ»¸öÐòÁнáÊø¡£Èç¹ûÒª±È½ÏµÄÁ½¸öÔªËر¾ÉíÊÇÏàͬÀàÐ͵ÄÐòÁÐ,ÔòµÝ¹éµØÖ´ÐÐ×Öµäʽ˳Ðò±È½Ï¡£Èç¹ûÁ½¸öÐòÁÐÖÐËùÓеĶÔÓ¦ÔªËض¼ÏàµÈ,ÔòÁ½¸öÐòÁÐÏàµÈ¡£Èç¹ûÒ»¸öÐòÁÐÊÇÁíÒ»¸öµÄ³õʼ×ÓÐòÁÐ,Ôò½Ï¶ÌµÄÐòÁпɱ»ÊÓΪ½ÏС(½ÏÉÙ)µÄÐòÁС£ ¶ÔÓÚ×Ö·û´®À´Ëµ,×Öµäʽ˳ÐòʹÓà Unicode ÂëλÐòºÅÅÅÐòµ¥¸ö×Ö·û¡£ÏÂÃæÁгöÁËһЩ±È½ÏÏàͬÀàÐÍÐòÁеÄÀý×Ó:
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
×¢Òâ,¶Ô²»Í¬ÀàÐ͵ĶÔÏóÀ´Ëµ,Ö»Òª´ý±È½ÏµÄ¶ÔÏóÌṩÁ˺ÏÊʵıȽϷ½·¨,¾Í¿ÉÒÔʹÓÃ?< ?ºÍ?> ?½øÐбȽϡ£ÀýÈç,»ìºÏÊýÖµÀàÐÍͨ¹ýÊýÖµ½øÐбȽÏ,ËùÒÔ,0 µÈÓÚ 0.0,µÈµÈ¡£·ñÔò,½âÊÍÆ÷²»»áËæ±ã¸ø³öÒ»¸ö¶Ô±È½á¹û,¶øÊÇ´¥·¢?TypeError?Òì³£¡£
?
7.?ÊäÈëÓëÊä³ö
³ÌÐòÊä³öÓм¸ÖÖÏÔʾ·½Ê½;Êý¾Ý¼È¿ÉÒÔÊä³ö¹©ÈËÔĶÁµÄÐÎʽ,Ò²¿ÉÒÔдÈëÎļþ±¸Óᣱ¾ÕÂ̽ÌÖһЩ¿ÉÓõķ½Ê½¡£
7.1.?¸ü¸´ÔÓµÄÊä³ö¸ñʽ
ÖÁ´Ë,ÎÒÃÇÒÑѧϰÁËÁ½ÖÖдÈëÖµµÄ·½·¨:±í´ïʽÓï¾ä?ºÍ?print()?º¯Êý¡£µÚÈýÖÖ·½·¨ÊÇʹÓÃÎļþ¶ÔÏóµÄ?write() ?·½·¨;±ê×¼Êä³öÎļþ³ÆΪ?sys.stdout ¡£Ïê¼û±ê×¼¿â²Î¿¼¡£
¶ÔÊä³ö¸ñʽµÄ¿ØÖƲ»Ö»ÊÇ´òÓ¡¿Õ¸ñ·Ö¸ôµÄÖµ,»¹ÐèÒª¸ü¶à·½Ê½¡£¸ñʽ»¯Êä³ö°üÀ¨ÒÔϼ¸ÖÖ·½·¨¡£
-
ʹÓÃ?¸ñʽ»¯×Ö·û´®×ÖÃæÖµ?,ÒªÔÚ×Ö·û´®¿ªÍ·µÄÒýºÅ/ÈýÒýºÅÇ°Ìí¼Ó?f ?»ò?F ?¡£ÔÚÕâÖÖ×Ö·û´®ÖÐ,¿ÉÒÔÔÚ?{ ?ºÍ?} ?×Ö·ûÖ®¼äÊäÈëÒýÓõıäÁ¿,»ò×ÖÃæÖµµÄ Python ±í´ïʽ¡£ >>> >>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'
-
×Ö·û´®µÄ?str.format()?·½·¨ÐèÒª¸ü¶àÊÖ¶¯²Ù×÷¡£¸Ã·½·¨Ò²ÓÃ?{ ?ºÍ?} ?±ê¼ÇÌæ»»±äÁ¿µÄλÖÃ,ËäÈ»ÕâÖÖ·½·¨Ö§³ÖÏêϸµÄ¸ñʽ»¯Ö¸Áî,µ«ÐèÒªÌṩ¸ñʽ»¯ÐÅÏ¢¡£ >>> >>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'
-
×îºó,»¹¿ÉÒÔÓÃ×Ö·û´®ÇÐƬºÍºÏ²¢²Ù×÷Íê³É×Ö·û´®´¦Àí²Ù×÷,´´½¨ÈκÎÅÅ°æ²¼¾Ö¡£×Ö·û´®ÀàÐÍ»¹Ö§³Ö½«×Ö·û´®°´¸ø¶¨Áпí½øÐÐÌî³ä,ÕâЩ·½·¨Ò²ºÜÓÐÓá£
Èç¹û²»ÐèÒª»¨ÉÚµÄÊä³ö,Ö»Ïë¿ìËÙÏÔʾ±äÁ¿½øÐе÷ÊÔ,¿ÉÒÔÓÃ?repr()?»ò?str()?º¯Êý°Ñֵת»¯Îª×Ö·û´®¡£
str()?º¯Êý·µ»Ø¹©ÈËÔĶÁµÄÖµ,repr()?ÔòÉú³ÉÊÊÓÚ½âÊÍÆ÷¶ÁÈ¡µÄÖµ(Èç¹ûûÓеÈЧµÄÓï·¨,ÔòÇ¿ÖÆÖ´ÐÐ?SyntaxError)¡£¶ÔÓÚûÓÐÖ§³Ö¹©ÈËÔĶÁչʾ½á¹ûµÄ¶ÔÏó,?str()?·µ»ØÓë?repr()?ÏàͬµÄÖµ¡£Ò»°ãÇé¿öÏÂ,Êý×Ö¡¢Áбí»ò×ÖµäµÈ½á¹¹µÄÖµ,ʹÓÃÕâÁ½¸öº¯ÊýÊä³öµÄ±íÏÖÐÎʽÊÇÒ»ÑùµÄ¡£×Ö·û´®ÓÐÁ½ÖÖ²»Í¬µÄ±íÏÖÐÎʽ¡£
ʾÀýÈçÏÂ:
>>>
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
string?Ä£¿é°üº¬?Template?Àà,ÌṩÁ˽«ÖµÌ滻Ϊ×Ö·û´®µÄÁíÒ»ÖÖ·½·¨¡£¸ÃÀàʹÓÃ?$x ?ռλ·û,²¢ÓÃ×ÖµäµÄÖµ½øÐÐÌæ»»,µ«¶Ô¸ñʽ¿ØÖƵÄÖ§³Ö±È½ÏÓÐÏÞ¡£
7.1.1.?¸ñʽ»¯×Ö·û´®×ÖÃæÖµ
¸ñʽ»¯×Ö·û´®×ÖÃæÖµ?(¼ò³ÆΪ f-×Ö·û´®)ÔÚ×Ö·û´®Ç°¼Óǰ׺?f ?»ò?F ,ͨ¹ý?{expression} ?±í´ïʽ,°Ñ Python ±í´ïʽµÄÖµÌí¼Óµ½×Ö·û´®ÄÚ¡£
¸ñʽ˵Ã÷·ûÊÇ¿ÉÑ¡µÄ,дÔÚ±í´ïʽºóÃæ,¿ÉÒÔ¸üºÃµØ¿ØÖƸñʽ»¯ÖµµÄ·½Ê½¡£ÏÂÀý½« pi ÉáÈ뵽СÊýµãºóÈýλ:
>>>
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
ÔÚ?':' ?ºó´«µÝÕûÊý,Ϊ¸Ã×Ö¶ÎÉèÖÃ×îС×Ö·û¿í¶È,³£ÓÃÓÚÁжÔÆë:
>>>
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
»¹ÓÐһЩÐÞÊηû¿ÉÒÔÔÚ¸ñʽ»¯Ç°×ª»»Öµ¡£?'!a' ?Ó¦ÓÃ?ascii()?,'!s' ?Ó¦ÓÃ?str(),'!r' ?Ó¦ÓÃ?repr():
>>>
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
¸ñʽ¹æ·¶²Î¿¼Ïê¼û²Î¿¼Ö¸ÄÏ?¸ñʽ¹æ¸ñÃÔÄãÓïÑÔ¡£
7.1.2.?×Ö·û´® format() ·½·¨
str.format()?·½·¨µÄ»ù±¾Ó÷¨ÈçÏÂËùʾ:
>>>
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
»¨À¨ºÅ¼°Ö®ÄÚµÄ×Ö·û(³ÆΪ¸ñʽ×Ö¶Î)±»Ì滻Ϊ´«µÝ¸ø?str.format()?·½·¨µÄ¶ÔÏó¡£»¨À¨ºÅÖеÄÊý×Ö±íʾ´«µÝ¸ø?str.format()?·½·¨µÄ¶ÔÏóËùÔÚµÄλÖá£
>>>
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
str.format()?·½·¨ÖÐʹÓùؼü×Ö²ÎÊýÃûÒýÓÃÖµ¡£
>>>
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
λÖòÎÊýºÍ¹Ø¼ü×Ö²ÎÊý¿ÉÒÔÈÎÒâ×éºÏ:
>>>
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred, and Georg.
Èç¹û²»Ïë·Ö²ð½Ï³¤µÄ¸ñʽ×Ö·û´®,×îºÃ°´Ãû³ÆÒýÓñäÁ¿½øÐиñʽ»¯,²»Òª°´Î»Öá£ÕâÏî²Ù×÷¿ÉÒÔͨ¹ý´«µÝ×Öµä,²¢Ó÷½À¨ºÅ?'[]' ?·ÃÎʼüÀ´Íê³É¡£
>>>
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
... 'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
This could also be done by passing the?table ?dictionary as keyword arguments with the?** ?notation.
>>>
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
ÓëÄÚÖú¯Êý?vars()?½áºÏʹÓÃʱ,ÕâÖÖ·½Ê½·Ç³£ÊµÓÃ,¿ÉÒÔ·µ»Ø°üº¬ËùÓоֲ¿±äÁ¿µÄ×ֵ䡣
ÀýÈç,ÏÂÃæµÄ´úÂëÉú³ÉÒ»×éÕûÆëµÄÁÐ,°üº¬¸ø¶¨ÕûÊý¼°Æäƽ·½ÓëÁ¢·½:
>>>
>>> for x in range(1, 11):
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
str.format()?½øÐÐ×Ö·û´®¸ñʽ»¯µÄÍêÕû¸ÅÊöÏê¼û?¸ñʽ×Ö·û´®Óï·¨?¡£
7.1.3.?ÊÖ¶¯¸ñʽ»¯×Ö·û´®
ÏÂÃæÊÇʹÓÃÊÖ¶¯¸ñʽ»¯·½Ê½ÊµÏÖµÄͬһ¸öƽ·½ºÍÁ¢·½µÄ±í:
>>>
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note use of 'end' on previous line
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
(×¢Òâ,ÿÁÐÖ®¼äµÄ¿Õ¸ñÊÇͨ¹ýʹÓÃ?print()?Ìí¼ÓµÄ:Ëü×ÜÔÚÆä²ÎÊý¼äÌí¼Ó¿Õ¸ñ¡£)
×Ö·û´®¶ÔÏóµÄ?str.rjust()?·½·¨Í¨¹ýÔÚ×ó²àÌî³ä¿Õ¸ñ,¶Ô¸ø¶¨¿í¶È×Ö¶ÎÖеÄ×Ö·û´®½øÐÐÓÒ¶ÔÆ롣ͬÀà·½·¨»¹ÓÐ?str.ljust()?ºÍ?str.center()?¡£ÕâЩ·½·¨²»Ð´ÈëÈκÎÄÚÈÝ,Ö»·µ»ØÒ»¸öÐÂ×Ö·û´®,Èç¹ûÊäÈëµÄ×Ö·û´®Ì«³¤,ËüÃDz»»á½Ø¶Ï×Ö·û´®,¶øÊÇÔÑù·µ»Ø;ËäÈ»ÕâÖÖ·½Ê½»áŪÂÒÁв¼¾Ö,µ«Ò²±ÈÁíÒ»ÖÖ·½·¨ºÃ,ºóÕßÔÚÏÔʾֵʱ¿ÉÄܲ»×¼È·(Èç¹ûÕæµÄÏë½Ø¶Ï×Ö·û´®,¿ÉÒÔʹÓÃ?x.ljust(n)[:n] ?ÕâÑùµÄÇÐƬ²Ù×÷ ¡£)
ÁíÒ»ÖÖ·½·¨ÊÇ?str.zfill()?,¸Ã·½·¨ÔÚÊý×Ö×Ö·û´®×ó±ßÌî³äÁã,ÇÒÄÜʶ±ðÕý¸ººÅ:
>>>
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
7.1.4.?¾Éʽ×Ö·û´®¸ñʽ»¯·½·¨
% ÔËËã·û(ÇóÓà·û)Ò²¿ÉÓÃÓÚ×Ö·û´®¸ñʽ»¯¡£¸ø¶¨?'string'?%?values ,Ôò?string ?ÖеÄ?% ?ʵÀý»áÒÔÁã¸ö»ò¶à¸ö?values ?ÔªËØÌæ»»¡£´Ë²Ù×÷±»³ÆΪ×Ö·û´®²åÖµ¡£ÀýÈç:
>>>
>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
printf ·ç¸ñµÄ×Ö·û´®¸ñʽ»¯?С½Ú½éÉܸü¶àÏà¹ØÄÚÈÝ¡£
7.2.?¶ÁдÎļþ
open()?·µ»ØÒ»¸ö?file object?,×ʹÓõÄÊÇÁ½¸öλÖòÎÊýºÍÒ»¸ö¹Ø¼ü×Ö²ÎÊý:open(filename,?mode,?encoding=None)
>>>
>>> f = open('workfile', 'w', encoding="utf-8")
µÚÒ»¸öʵ²ÎÊÇÎļþÃû×Ö·û´®¡£µÚ¶þ¸öʵ²ÎÊÇ°üº¬ÃèÊöÎļþʹÓ÷½Ê½×Ö·ûµÄ×Ö·û´®¡£mode?µÄÖµ°üÀ¨?'r' ?,±íʾÎļþÖ»ÄܶÁÈ¡;'w' ?±íʾֻÄÜдÈë(ÏÖÓÐͬÃûÎļþ»á±»¸²¸Ç);'a' ?±íʾ´ò¿ªÎļþ²¢×·¼ÓÄÚÈÝ,ÈκÎдÈëµÄÊý¾Ý»á×Ô¶¯Ìí¼Óµ½Îļþĩβ¡£'r+' ?±íʾ´ò¿ªÎļþ½øÐжÁд¡£mode?ʵ²ÎÊÇ¿ÉÑ¡µÄ,Ê¡ÂÔʱµÄĬÈÏֵΪ?'r' ¡£
ͨ³£Çé¿öÏÂ,ÎļþÊÇÒÔ?text mode?´ò¿ªµÄ,Ò²¾ÍÊÇ˵,Äã´ÓÎļþÖжÁд×Ö·û´®,ÕâЩ×Ö·û´®ÊÇÒÔÌض¨µÄ?encoding?±àÂëµÄ¡£Èç¹ûûÓÐÖ¸¶¨?encoding?,ĬÈϵÄÊÇÓëƽ̨ÓйصÄ(¼û?open()?)¡£ÒòΪ UTF-8 ÊÇÏÖ´úÊÂʵÉϵıê×¼,³ý·ÇÄãÖªµÀÄãÐèҪʹÓÃÒ»¸ö²»Í¬µÄ±àÂë,·ñÔò½¨ÒéʹÓÃ?encoding="utf-8" ?¡£ÔÚģʽºóÃæ¼ÓÉÏÒ»¸ö?'b' ?,¿ÉÒÔÓÃ?binary mode?´ò¿ªÎļþ¡£¶þ½øÖÆģʽµÄÊý¾ÝÊÇÒÔ?bytes?¶ÔÏóµÄÐÎʽ¶ÁдµÄ¡£ÔÚ¶þ½øÖÆģʽÏ´ò¿ªÎļþʱ,Äã²»ÄÜÖ¸¶¨?encoding?¡£
ÔÚÎı¾Ä£Ê½Ï¶ÁÈ¡Îļþʱ,ĬÈÏ°Ñƽ̨Ìض¨µÄÐнáÊø·û(Unix ÉÏΪ?\n , Windows ÉÏΪ?\r\n )ת»»Îª?\n ¡£ÔÚÎı¾Ä£Ê½ÏÂдÈëÊý¾Ýʱ,ĬÈÏ°Ñ?\n ?ת»»»Øƽ̨Ìض¨½áÊø·û¡£ÕâÖÖ²Ù×÷·½Ê½ÔÚºǫ́ÐÞ¸ÄÎļþÊý¾Ý¶ÔÎı¾ÎļþÀ´ËµÃ»ÓÐÎÊÌâ,µ«»áÆÆ»µ?JPEG ?»ò?EXE ?µÈ¶þ½øÖÆÎļþÖеÄÊý¾Ý¡£×¢Òâ,ÔÚ¶Áд´ËÀàÎļþʱ,Ò»¶¨ÒªÊ¹Óöþ½øÖÆģʽ¡£
ÔÚ´¦ÀíÎļþ¶ÔÏóʱ,×îºÃʹÓÃ?with?¹Ø¼ü×Ö¡£ÓŵãÊÇ,×Ó¾äÌå½áÊøºó,Îļþ»áÕýÈ·¹Ø±Õ,¼´±ã´¥·¢Òì³£Ò²¿ÉÒÔ¡£¶øÇÒ,ʹÓÃ?with ?Ïà±ÈµÈЧµÄ?try-finally?´úÂë¿éÒª¼ò¶ÌµÃ¶à:
>>>
>>> with open('workfile', encoding="utf-8") as f:
... read_data = f.read()
>>> # We can check that the file has been automatically closed.
>>> f.closed
True
Èç¹ûûÓÐʹÓÃ?with?¹Ø¼ü×Ö,ÔòÓ¦µ÷ÓÃ?f.close() ?¹Ø±ÕÎļþ,¼´¿ÉÊÍ·ÅÎļþÕ¼ÓõÄϵͳ×ÊÔ´¡£
¾¯¸æ
µ÷ÓÃ?f.write() ?ʱ,δʹÓÃ?with ?¹Ø¼ü×Ö,»òδµ÷ÓÃ?f.close() ,¼´Ê¹³ÌÐòÕý³£Í˳ö,Ò²**¿ÉÄÜ** µ¼ÖÂ?f.write() ?µÄ²ÎÊýûÓÐÍêȫдÈë´ÅÅÌ¡£
ͨ¹ý?with?Óï¾ä,»òµ÷ÓÃ?f.close() ?¹Ø±ÕÎļþ¶ÔÏóºó,ÔÙ´ÎʹÓøÃÎļþ¶ÔÏ󽫻áʧ°Ü¡£
>>>
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
7.2.1.?Îļþ¶ÔÏóµÄ·½·¨
±¾½ÚÏÂÎÄÖеÄÀý×Ó¼Ù¶¨ÒÑ´´½¨?f ?Îļþ¶ÔÏó¡£
f.read(size) ?¿ÉÓÃÓÚ¶ÁÈ¡ÎļþÄÚÈÝ,Ëü»á¶ÁȡһЩÊý¾Ý,²¢·µ»Ø×Ö·û´®(Îı¾Ä£Ê½),»ò×Ö½Ú´®¶ÔÏó(ÔÚ¶þ½øÖÆģʽÏÂ)¡£?size?ÊÇ¿ÉÑ¡µÄÊýÖµ²ÎÊý¡£Ê¡ÂÔ?size?»ò?size?Ϊ¸ºÊýʱ,¶ÁÈ¡²¢·µ»ØÕû¸öÎļþµÄÄÚÈÝ;Îļþ´óСÊÇÄÚ´æµÄÁ½±¶Ê±,»á³öÏÖÎÊÌâ¡£size?È¡ÆäËûֵʱ,¶ÁÈ¡²¢·µ»Ø×î¶à?size?¸ö×Ö·û(Îı¾Ä£Ê½)»ò?size?¸ö×Ö½Ú(¶þ½øÖÆģʽ)¡£ÈçÒѵ½´ïÎļþĩβ,f.read() ?·µ»Ø¿Õ×Ö·û´®('' )¡£
>>>
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
f.readline() ?´ÓÎļþÖжÁÈ¡µ¥ÐÐÊý¾Ý;×Ö·û´®Ä©Î²±£Áô»»Ðзû(\n ),Ö»ÓÐÔÚÎļþ²»ÒÔ»»Ðзû½áβʱ,ÎļþµÄ×îºóÒ»ÐвŻáÊ¡ÂÔ»»Ðзû¡£ÕâÖÖ·½Ê½È÷µ»ØÖµÇåÎúÃ÷È·;Ö»Òª?f.readline() ?·µ»Ø¿Õ×Ö·û´®,¾Í±íʾÒѾµ½´ïÁËÎļþĩβ,¿ÕÐÐʹÓÃ?'\n' ?±íʾ,¸Ã×Ö·û´®Ö»°üº¬Ò»¸ö»»Ðзû¡£
>>>
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
´ÓÎļþÖжÁÈ¡¶àÐÐʱ,¿ÉÒÔÓÃÑ»·±éÀúÕû¸öÎļþ¶ÔÏó¡£ÕâÖÖ²Ù×÷ÄܸßЧÀûÓÃÄÚ´æ,¿ìËÙ,ÇÒ´úÂë¼òµ¥:
>>>
>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
ÈçÐèÒÔÁбíÐÎʽ¶ÁÈ¡ÎļþÖеÄËùÓÐÐÐ,¿ÉÒÔÓÃ?list(f) ?»ò?f.readlines() ¡£
f.write(string) ?°Ñ?string?µÄÄÚÈÝдÈëÎļþ,²¢·µ»ØдÈëµÄ×Ö·ûÊý¡£
>>>
>>> f.write('This is a test\n')
15
дÈëÆäËûÀàÐ͵ĶÔÏóÇ°,ÒªÏÈ°ÑËüÃÇת»¯Îª×Ö·û´®(Îı¾Ä£Ê½)»ò×Ö½Ú¶ÔÏó(¶þ½øÖÆģʽ):
>>>
>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f.write(s)
18
f.tell() ?·µ»ØÕûÊý,¸ø³öÎļþ¶ÔÏóÔÚÎļþÖеĵ±Ç°Î»ÖÃ,±íʾΪ¶þ½øÖÆģʽÏÂʱ´ÓÎļþ¿ªÊ¼µÄ×Ö½ÚÊý,ÒÔ¼°Îı¾Ä£Ê½ÏµÄÒâÒå²»Ã÷µÄÊý×Ö¡£
f.seek(offset,?whence) ?¿ÉÒԸıäÎļþ¶ÔÏóµÄλÖá£Í¨¹ýÏò²Î¿¼µãÌí¼Ó?offset?¼ÆËãλÖÃ;²Î¿¼µãÓÉ?whence?²ÎÊýÖ¸¶¨¡£?whence?ֵΪ 0 ʱ,±íʾ´ÓÎļþ¿ªÍ·¼ÆËã,1 ±íʾʹÓõ±Ç°ÎļþλÖÃ,2 ±íʾʹÓÃÎļþĩβ×÷Ϊ²Î¿¼µã¡£Ê¡ÂÔ?whence?ʱ,ÆäĬÈÏֵΪ 0,¼´Ê¹ÓÃÎļþ¿ªÍ·×÷Ϊ²Î¿¼µã¡£
>>>
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5) # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'
ÔÚÎı¾Îļþ(ģʽ×Ö·û´®Î´Ê¹ÓÃ?b ?ʱ´ò¿ªµÄÎļþ)ÖÐ,Ö»ÔÊÐíÏà¶ÔÓÚÎļþ¿ªÍ·ËÑË÷(ʹÓÃ?seek(0,?2) ?ËÑË÷µ½ÎļþĩβÊǸöÀýÍâ),ΨһÓÐЧµÄ?offset?ÖµÊÇÄÜ´Ó?f.tell() ?Öзµ»ØµÄ,»ò 0¡£ÆäËû?offset?Öµ¶¼»á²úÉú䶨ÒåµÄÐÐΪ¡£
Îļþ¶ÔÏó»¹Ö§³Ö?isatty() ?ºÍ?truncate() ?µÈ·½·¨,µ«²»³£ÓÃ;Îļþ¶ÔÏóµÄÍêÕûÖ¸ÄÏÏê¼û¿â²Î¿¼¡£
7.2.2.?ʹÓÃ?json?±£´æ½á¹¹»¯Êý¾Ý
´ÓÎļþдÈë»ò¶ÁÈ¡×Ö·û´®ºÜ¼òµ¥,Êý×ÖÔòÉÔÏÔÂé·³,ÒòΪ?read() ?·½·¨Ö»·µ»Ø×Ö·û´®,ÕâЩ×Ö·û´®±ØÐë´«µÝ¸ø?int()?ÕâÑùµÄº¯Êý,½ÓÊÜ?'123' ?ÕâÑùµÄ×Ö·û´®,²¢·µ»ØÊý×ÖÖµ 123¡£±£´æǶÌ×ÁÐ±í¡¢×ÖµäµÈ¸´ÔÓÊý¾ÝÀàÐÍʱ,ÊÖ¶¯½âÎöºÍÐòÁл¯µÄ²Ù×÷·Ç³£¸´ÔÓ¡£
Python Ö§³Ö?JSON (JavaScript Object Notation)?ÕâÖÖÁ÷ÐÐÊý¾Ý½»»»¸ñʽ,Óû§ÎÞÐèûÍêûÁ˵رàд¡¢µ÷ÊÔ´úÂë,²ÅÄܰѸ´ÔÓµÄÊý¾ÝÀàÐͱ£´æµ½Îļþ¡£json?±ê׼ģ¿é²ÉÓà Python Êý¾Ý²ã´Î½á¹¹,²¢½«Ö®×ª»»Îª×Ö·û´®±íʾÐÎʽ;Õâ¸ö¹ý³Ì³ÆΪ?serializing?(ÐòÁл¯)¡£´Ó×Ö·û´®±íʾÖÐÖؽ¨Êý¾Ý³ÆΪ?deserializing?(½âÐò»¯)¡£ÔÚÐòÁл¯ºÍ½âÐò»¯Ö®¼ä,±íʾ¶ÔÏóµÄ×Ö·û´®¿ÉÄÜÒѾ´æ´¢ÔÚÎļþ»òÊý¾ÝÖÐ,»òͨ¹ýÍøÂçÁ¬½Ó·¢Ë͵½Ô¶·½ µÄ»úÆ÷¡£
±¸×¢
JSON ¸ñʽͨ³£ÓÃÓÚÏÖ´úÓ¦ÓóÌÐòµÄÊý¾Ý½»»»¡£³ÌÐòÔ±ÔçÒѶÔËü¶úÊìÄÜÏê,¿ÉνÊǽ»»¥²Ù×÷µÄ²»¶þ֮ѡ¡£
Ö»ÐèÒ»Ðмòµ¥µÄ´úÂë¼´¿É²é¿´Ä³¸ö¶ÔÏóµÄ JSON ×Ö·û´®±íÏÖÐÎʽ:
>>>
>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'
dumps()?º¯Êý»¹ÓÐÒ»¸ö±äÌå,?dump()?,ËüÖ»½«¶ÔÏóÐòÁл¯Îª?text file?¡£Òò´Ë,Èç¹û?f ?ÊÇ?text file?¶ÔÏó,¿ÉÒÔÕâÑù×ö:
json.dump(x, f)
ÒªÔٴνâÂë¶ÔÏó,Èç¹û?f ?ÊÇÒÑ´ò¿ª¡¢¹©¶ÁÈ¡µÄ?binary file?»ò?text file?¶ÔÏó:
x = json.load(f)
±¸×¢
JSONÎļþ±ØÐëÒÔUTF-8±àÂë¡£µ±´ò¿ªJSONÎļþ×÷Ϊһ¸ö?text file?ÓÃÓÚ¶Áдʱ,ʹÓÃ?encoding="utf-8" ?¡£
ÕâÖÖ¼òµ¥µÄÐòÁл¯¼¼Êõ¿ÉÒÔ´¦ÀíÁбíºÍ×Öµä,µ«ÔÚ JSON ÖÐÐòÁл¯ÈÎÒâÀàµÄʵÀý,ÔòÐèÒª¸¶³ö¶îÍâŬÁ¦¡£json?Ä£¿éµÄ²Î¿¼°üº¬¶Ô´ËµÄ½âÊÍ¡£
²Î¼û
pickle?- ·â´æÄ£¿é
Óë?JSON?²»Í¬,pickle?ÊÇÒ»ÖÖÔÊÐí¶Ô¸´ÔÓ Python ¶ÔÏó½øÐÐÐòÁл¯µÄÐÒé¡£Òò´Ë,ËüΪ Python ËùÌØÓÐ,²»ÄÜÓÃÓÚÓëÆäËûÓïÑÔ±àдµÄÓ¦ÓóÌÐòͨÐÅ¡£Ä¬ÈÏÇé¿öÏÂËüÒ²ÊDz»°²È«µÄ:Èç¹û½âÐò»¯µÄÊý¾ÝÊÇÓÉÊֶθßÃ÷µÄ¹¥»÷Õß¾«ÐÄÉè¼ÆµÄ,ÕâÖÖ²»ÊÜÐÅÈÎÀ´Ô´µÄ pickle Êý¾Ý¿ÉÒÔÖ´ÐÐÈÎÒâ´úÂë¡£
8.?´íÎóºÍÒì³£
ÖÁ´Ë,±¾½Ì³Ì»¹Î´ÉîÈë½éÉÜ´íÎóÐÅÏ¢,µ«Èç¹ûÄúÊäÈë¹ý±¾½Ì³ÌÇ°ÎÄÖеÄÀý×Ó,Ó¦¸ÃÒѾ¿´µ½¹ýһЩ´íÎóÐÅÏ¢¡£Ä¿Ç°,(ÖÁÉÙ)ÓÐÁ½ÖÖ²»Í¬´íÎó:¾ä·¨´íÎó?ºÍ?Òì³£¡£
8.1.?¾ä·¨´íÎó
¾ä·¨´íÎóÓֳƽâÎö´íÎó,ÊÇѧϰ Python ʱ×î³£¼ûµÄ´íÎó:
>>>
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
½âÎöÆ÷»á¸´ÏÖ³öÏ־䷨´íÎóµÄ´úÂëÐÐ,²¢ÓÃС¡°¼ýÍ·¡±Ö¸ÏòÐÐÀï¼ì²âµ½µÄµÚÒ»¸ö´íÎó¡£´íÎóÊÇÓɼýÍ·?ÉÏ·½?µÄ token ´¥·¢µÄ(ÖÁÉÙÊÇÔÚÕâÀï¼ì²â³öµÄ):±¾ÀýÖÐ,ÔÚ?print()?º¯ÊýÖмì²âµ½´íÎó,ÒòΪ,ÔÚËüÇ°ÃæȱÉÙðºÅ(':' ) ¡£´íÎóÐÅÏ¢»¹Êä³öÎļþÃûÓëÐкÅ,ÔÚʹÓýű¾Îļþʱ,¾Í¿ÉÒÔÖªµÀÈ¥ÄÄÀï²é´í¡£
8.2.?Òì³£
¼´Ê¹Óï¾ä»ò±í´ïʽʹÓÃÁËÕýÈ·µÄÓï·¨,Ö´ÐÐʱÈÔ¿ÉÄÜ´¥·¢´íÎó¡£Ö´ÐÐʱ¼ì²âµ½µÄ´íÎó³ÆΪ?Òì³£,Òì³£²»Ò»¶¨µ¼ÖÂÑÏÖصĺó¹û:ºÜ¿ìÎÒÃǾÍÄÜѧ»áÈçºÎ´¦Àí Python µÄÒì³£¡£´ó¶àÊýÒì³£²»»á±»³ÌÐò´¦Àí,¶øÊÇÏÔʾÏÂÁдíÎóÐÅÏ¢:
>>>
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
´íÎóÐÅÏ¢µÄ×îºóÒ»ÐÐ˵Ã÷³ÌÐòÓöµ½ÁËʲôÀàÐ͵ĴíÎó¡£Òì³£Óв»Í¬µÄÀàÐÍ,¶øÀàÐÍÃû³Æ»á×÷Ϊ´íÎóÐÅÏ¢µÄÒ»²¿·ÖÖдòÓ¡³öÀ´:ÉÏÊöʾÀýÖеÄÒì³£ÀàÐÍÒÀ´ÎÊÇ:ZeroDivisionError,?NameError?ºÍ?TypeError¡£×÷ΪÒì³£ÀàÐÍ´òÓ¡µÄ×Ö·û´®ÊÇ·¢ÉúµÄÄÚÖÃÒì³£µÄÃû³Æ¡£¶ÔÓÚËùÓÐÄÚÖÃÒì³£¶¼ÊÇÈç´Ë,µ«¶ÔÓÚÓû§¶¨ÒåµÄÒì³£Ôò²»Ò»¶¨Èç´Ë(ËäÈ»ÕâÖֹ淶ºÜÓÐÓÃ)¡£±ê×¼µÄÒì³£ÀàÐÍÊÇÄÚÖõıêʶ·û(²»ÊDZ£Áô¹Ø¼ü×Ö)¡£
´ËÐÐÆäÓಿ·Ö¸ù¾ÝÒì³£ÀàÐÍ,½áºÏ³ö´íÔÒò,˵Ã÷´íÎóϸ½Ú¡£
´íÎóÐÅÏ¢¿ªÍ·ÓöÑÕ»»ØËÝÐÎʽչʾ·¢ÉúÒì³£µÄÓï¾³¡£Ò»°ã»áÁгöÔ´´úÂëÐеĶÑÕ»»ØËÝ;µ«²»»áÏÔʾ´Ó±ê×¼ÊäÈë¶ÁÈ¡µÄÐС£
ÄÚÖÃÒì³£?ÁгöÁËÄÚÖÃÒì³£¼°Æ京Òå¡£
8.3.?Òì³£µÄ´¦Àí
¿ÉÒÔ±àд³ÌÐò´¦ÀíÑ¡¶¨µÄÒì³£¡£ÏÂÀý»áÒªÇóÓû§Ò»Ö±ÊäÈëÄÚÈÝ,Ö±µ½ÊäÈëÓÐЧµÄÕûÊý,µ«ÔÊÐíÓû§ÖжϳÌÐò(ʹÓÃ?Control-C?»ò²Ù×÷ϵͳ֧³ÖµÄÆäËû²Ù×÷);×¢Òâ,Óû§ÖжϳÌÐò»á´¥·¢?KeyboardInterrupt?Òì³£¡£
>>>
>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
try?Óï¾äµÄ¹¤×÷ÔÀíÈçÏÂ:
-
Ê×ÏÈ,Ö´ÐÐ?try ×Ó¾ä?(try?ºÍ?except?¹Ø¼ü×ÖÖ®¼äµÄ(¶àÐÐ)Óï¾ä)¡£ -
Èç¹ûûÓд¥·¢Òì³£,ÔòÌø¹ý?except ×Ó¾ä,try?Óï¾äÖ´ÐÐÍê±Ï¡£ -
Èç¹ûÔÚÖ´ÐÐ?try?×Ó¾äʱ·¢ÉúÁËÒì³£,ÔòÌø¹ý¸Ã×Ó¾äÖÐʣϵIJ¿·Ö¡£ Èç¹ûÒì³£µÄÀàÐÍÓë?except?¹Ø¼ü×ÖºóÖ¸¶¨µÄÒì³£ÏàÆ¥Åä,Ôò»áÖ´ÐÐ?except ×Ó¾ä,È»ºóÌøµ½ try/except ´úÂë¿éÖ®ºó¼ÌÐøÖ´ÐС£ -
Èç¹û·¢ÉúµÄÒì³£Óë?except ×Ó¾ä?ÖÐÖ¸¶¨µÄÒì³£²»Æ¥Åä,ÔòËü»á±»´«µÝµ½ÍⲿµÄ?try?Óï¾äÖÐ;Èç¹ûûÓÐÕÒµ½´¦Àí³ÌÐò,ÔòËüÊÇÒ»¸ö?δ´¦ÀíÒì³£?ÇÒÖ´Ðн«ÖÕÖ¹²¢Êä³öÈçÉÏËùʾµÄÏûÏ¢¡£
try?Óï¾ä¿ÉÒÔÓжà¸ö?except ×Ó¾ä?À´Îª²»Í¬µÄÒì³£Ö¸¶¨´¦Àí³ÌÐò¡£ µ«×î¶àÖ»ÓÐÒ»¸ö´¦Àí³ÌÐò»á±»Ö´ÐС£ ´¦Àí³ÌÐòÖ»´¦Àí¶ÔÓ¦µÄ?try ×Ó¾ä?Öз¢ÉúµÄÒì³£,¶ø²»´¦Àíͬһ?try ?Óï¾äÄÚÆäËû´¦Àí³ÌÐòÖеÄÒì³£¡£?except ×Ó¾ä?¿ÉÒÔÓôøÔ²À¨ºÅµÄÔª×éÀ´Ö¸¶¨¶à¸öÒì³£,ÀýÈç:
... except (RuntimeError, TypeError, NameError):
... pass
Èç¹û·¢ÉúµÄÒì³£Óë?except?×Ó¾äÖеÄÀàÊÇͬһ¸öÀà»òÊÇËüµÄ»ùÀàʱ,Ôò¸ÃÀàÓë¸ÃÒì³£Ïà¼æÈÝ(·´Ö®Ôò²»³ÉÁ¢ --- ÁгöÅÉÉúÀàµÄ?except ×Ó¾ä?Óë»ùÀ಻¼æÈÝ)¡£ ÀýÈç,ÏÂÃæµÄ´úÂ뽫ÒÀ´Î´òÓ¡ B, C, D:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
Çë×¢ÒâÈç¹ûµßµ¹?except ×Ó¾ä?µÄ˳Ðò(°Ñ?except?B ?·ÅÔÚ×îÇ°),Ôò»áÊä³ö B, B, B --- ¼´´¥·¢Á˵ÚÒ»¸öÆ¥ÅäµÄ?except ×Ӿ䡣
When an exception occurs, it may have associated values, also known as the exception's?arguments. The presence and types of the arguments depend on the exception type.
The?except clause?may specify a variable after the exception name. The variable is bound to the exception instance which typically has an?args ?attribute that stores the arguments. For convenience, builtin exception types define?__str__() ?to print all the arguments without explicitly accessing?.args .
>>>
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) # the exception instance
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x, y = inst.args # unpack args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
The exception's?__str__() ?output is printed as the last part ('detail') of the message for unhandled exceptions.
BaseException?is the common base class of all exceptions. One of its subclasses,?Exception, is the base class of all the non-fatal exceptions. Exceptions which are not subclasses of?Exception?are not typically handled, because they are used to indicate that the program should terminate. They include?SystemExit?which is raised by?sys.exit()?and?KeyboardInterrupt?which is raised when a user wishes to interrupt the program.
Exception?can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on.
The most common pattern for handling?Exception?is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well):
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error:", err)
except ValueError:
print("Could not convert data to an integer.")
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
raise
try?...?except?Óï¾ä¾ßÓпÉÑ¡µÄ?else ×Ó¾ä,¸Ã×Ó¾äÈç¹û´æÔÚ,Ëü±ØÐë·ÅÔÚËùÓÐ?except ×Ó¾ä?Ö®ºó¡£ ËüÊÊÓÃÓÚ?try ×Ó¾ä?ûÓÐÒý·¢Òì³£µ«ÓÖ±ØÐëÒªÖ´ÐеĴúÂë¡£ ÀýÈç:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
ʹÓÃ?else ?×Ó¾ä±ÈÏò?try?×Ó¾äÌí¼Ó¶îÍâµÄ´úÂëÒªºÃ,¿ÉÒÔ±ÜÃâÒâÍⲶ»ñ·Ç?try ?...?except ?Óï¾ä±£»¤µÄ´úÂë´¥·¢µÄÒì³£¡£
Exception handlers do not handle only exceptions that occur immediately in the?try clause, but also those that occur inside functions that are called (even indirectly) in the?try clause. For example:
>>>
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero
8.4.?´¥·¢Òì³£
raise?Óï¾äÖ§³ÖÇ¿ÖÆ´¥·¢Ö¸¶¨µÄÒì³£¡£ÀýÈç:
>>>
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
The sole argument to?raise?indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from?BaseException, such as?Exception?or one of its subclasses). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:
raise ValueError # shorthand for 'raise ValueError()'
Èç¹ûÖ»ÏëÅжÏÊÇ·ñ´¥·¢ÁËÒì³£,µ«²¢²»´òËã´¦Àí¸ÃÒì³£,Ôò¿ÉÒÔʹÓøü¼òµ¥µÄ?raise?Óï¾äÖØд¥·¢Òì³£:
>>>
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
8.5.?Òì³£Á´
raise?Óï¾äÖ§³Ö¿ÉÑ¡µÄ?from?×Ó¾ä,¸Ã×Ó¾äÓÃÓÚÆôÓÃÁ´Ê½Òì³£¡£ ÀýÈç:
# exc must be exception instance or None.
raise RuntimeError from exc
ת»»Ò쳣ʱ,ÕâÖÖ·½Ê½ºÜÓÐÓá£ÀýÈç:
>>>
>>> def func():
... raise ConnectionError
...
>>> try:
... func()
... except ConnectionError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
ConnectionError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database
Òì³£Á´»áÔÚ?except?»ò?finally?×Ó¾äÄÚ²¿Òý·¢Ò쳣ʱ×Ô¶¯Éú³É¡£ Õâ¿ÉÒÔͨ¹ýʹÓÃ?from?None ?ÕâÑùµÄд·¨À´½ûÓÃ:
>>>
>>> try:
... open('database.sqlite')
... except OSError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError
Òì³£Á´»úÖÆÏê¼û?ÄÚÖÃÒì³£¡£
8.6.?Óû§×Ô¶¨ÒåÒì³£
³ÌÐò¿ÉÒÔͨ¹ý´´½¨ÐµÄÒì³£ÀàÃüÃû×Ô¼ºµÄÒì³£(Python ÀàµÄÄÚÈÝÏê¼û?Àà)¡£²»ÂÛÊÇÒÔÖ±½Ó»¹ÊǼä½ÓµÄ·½Ê½,Òì³£¶¼Ó¦´Ó?Exception?ÀàÅÉÉú¡£
Òì³£Àà¿ÉÒÔ±»¶¨Òå³ÉÄÜ×öÆäËûÀàËùÄÜ×öµÄÈκÎÊÂ,µ«Í¨³£Ó¦µ±±£³Ö¼òµ¥,ËüÍùÍùÖ»ÌṩһЩÊôÐÔ,ÔÊÐíÏàÓ¦µÄÒì³£´¦Àí³ÌÐòÌáÈ¡ÓйشíÎóµÄÐÅÏ¢¡£
´ó¶àÊýÒì³£ÃüÃû¶¼ÒÔ ¡°Error¡± ½áβ,ÀàËƱê×¼Òì³£µÄÃüÃû¡£
Many standard modules define their own exceptions to report errors that may occur in functions they define.
8.7.?¶¨ÒåÇåÀí²Ù×÷
try?Óï¾ä»¹ÓÐÒ»¸ö¿ÉÑ¡×Ó¾ä,ÓÃÓÚ¶¨ÒåÔÚËùÓÐÇé¿ö϶¼±ØÐëÒªÖ´ÐеÄÇåÀí²Ù×÷¡£ÀýÈç:
>>>
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
Èç¹û´æÔÚ?finally?×Ó¾ä,Ôò?finally ?×Ó¾äÊÇ?try?Óï¾ä½áÊøÇ°Ö´ÐеÄ×îºóÒ»ÏîÈÎÎñ¡£²»ÂÛ?try ?Óï¾äÊÇ·ñ´¥·¢Òì³£,¶¼»áÖ´ÐÐ?finally ?×Ӿ䡣ÒÔÏÂÄÚÈݽéÉÜÁ˼¸ÖֱȽϸ´ÔӵĴ¥·¢Òì³£Çé¾°:
-
Èç¹ûÖ´ÐÐ?try ?×Ó¾äÆڼ䴥·¢ÁËij¸öÒì³£,Ôòij¸ö?except?×Ó¾äÓ¦´¦Àí¸ÃÒì³£¡£Èç¹û¸ÃÒ쳣ûÓÐ?except ?×Ӿ䴦Àí,ÔÚ?finally ?×Ó¾äÖ´Ðкó»á±»ÖØд¥·¢¡£ -
except ?»ò?else ?×Ó¾äÖ´ÐÐÆÚ¼äÒ²»á´¥·¢Òì³£¡£ ͬÑù,¸ÃÒì³£»áÔÚ?finally ?×Ó¾äÖ´ÐÐÖ®ºó±»ÖØд¥·¢¡£ -
Èç¹û?finally ?×Ó¾äÖаüº¬?break¡¢continue?»ò?return?µÈÓï¾ä,Òì³£½«²»»á±»ÖØÐÂÒý·¢¡£ -
Èç¹ûÖ´ÐÐ?try ?Óï¾äʱÓöµ½?break,¡¢continue?»ò?return?Óï¾ä,Ôò?finally ?×Ó¾äÔÚÖ´ÐÐ?break ¡¢continue ?»ò?return ?Óï¾ä֮ǰִÐС£ -
Èç¹û?finally ?×Ó¾äÖаüº¬?return ?Óï¾ä,Ôò·µ»ØÖµÀ´×Ô?finally ?×Ó¾äµÄij¸ö?return ?Óï¾äµÄ·µ»ØÖµ,¶ø²»ÊÇÀ´×Ô?try ?×Ó¾äµÄ?return ?Óï¾äµÄ·µ»ØÖµ¡£
ÀýÈç:
>>>
>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
ÕâÊÇÒ»¸ö±È½Ï¸´ÔÓµÄÀý×Ó:
>>>
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
ÈçÉÏËùʾ,ÈκÎÇé¿ö϶¼»áÖ´ÐÐ?finally?×Ӿ䡣except?×Ӿ䲻´¦ÀíÁ½¸ö×Ö·û´®Ïà³ý´¥·¢µÄ?TypeError,Òò´Ë»áÔÚ?finally ?×Ó¾äÖ´Ðкó±»ÖØд¥·¢¡£
ÔÚʵ¼ÊÓ¦ÓóÌÐòÖÐ,finally?×Ó¾ä¶ÔÓÚÊÍ·ÅÍⲿ×ÊÔ´(ÀýÈçÎļþ»òÕßÍøÂçÁ¬½Ó)·Ç³£ÓÐÓÃ,ÎÞÂÛÊÇ·ñ³É¹¦Ê¹ÓÃ×ÊÔ´¡£
8.8.?Ô¤¶¨ÒåµÄÇåÀí²Ù×÷
ijЩ¶ÔÏó¶¨ÒåÁ˲»ÐèÒª¸Ã¶ÔÏóʱҪִÐеıê×¼ÇåÀí²Ù×÷¡£ÎÞÂÛʹÓøöÔÏóµÄ²Ù×÷ÊÇ·ñ³É¹¦,¶¼»áÖ´ÐÐÇåÀí²Ù×÷¡£±ÈÈç,ÏÂÀýÒª´ò¿ªÒ»¸öÎļþ,²¢Êä³öÎļþÄÚÈÝ:
for line in open("myfile.txt"):
print(line, end="")
Õâ¸ö´úÂëµÄÎÊÌâÔÚÓÚ,Ö´ÐÐÍê´úÂëºó,ÎļþÔÚÒ»¶Î²»È·¶¨µÄʱ¼äÄÚ´¦ÓÚ´ò¿ª×´Ì¬¡£ÔÚ¼òµ¥½Å±¾ÖÐÕâûÓÐÎÊÌâ,µ«¶ÔÓڽϴóµÄÓ¦ÓóÌÐòÀ´Ëµ¿ÉÄÜ»á³öÎÊÌâ¡£with?Óï¾äÖ§³ÖÒÔ¼°Ê±¡¢ÕýÈ·µÄÇåÀíµÄ·½Ê½Ê¹ÓÃÎļþ¶ÔÏó:
with open("myfile.txt") as f:
for line in f:
print(line, end="")
Óï¾äÖ´ÐÐÍê±Ïºó,¼´Ê¹ÔÚ´¦ÀíÐÐʱÓöµ½ÎÊÌâ,¶¼»á¹Ø±ÕÎļþ?f¡£ºÍÎļþÒ»Ñù,Ö§³ÖÔ¤¶¨ÒåÇåÀí²Ù×÷µÄ¶ÔÏó»áÔÚÎĵµÖÐÖ¸³öÕâÒ»µã¡£
8.9.?Raising and Handling Multiple Unrelated Exceptions
There are situations where it is necessary to report several exceptions that have occurred. This it often the case in concurrency frameworks, when several tasks may have failed in parallel, but there are also other use cases where it is desirable to continue execution and collect multiple errors rather than raise the first exception.
The builtin?ExceptionGroup?wraps a list of exception instances so that they can be raised together. It is an exception itself, so it can be caught like any other exception.
>>>
>>> def f():
... excs = [OSError('error 1'), SystemError('error 2')]
... raise ExceptionGroup('there were problems', excs)
...
>>> f()
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| File "<stdin>", line 3, in f
| ExceptionGroup: there were problems
+-+---------------- 1 ----------------
| OSError: error 1
+---------------- 2 ----------------
| SystemError: error 2
+------------------------------------
>>> try:
... f()
... except Exception as e:
... print(f'caught {type(e)}: e')
...
caught <class 'ExceptionGroup'>: e
>>>
By using?except* ?instead of?except , we can selectively handle only the exceptions in the group that match a certain type. In the following example, which shows a nested exception group, each?except* ?clause extracts from the group exceptions of a certain type while letting all other exceptions propagate to other clauses and eventually to be reraised.
>>>
>>> def f():
... raise ExceptionGroup("group1",
... [OSError(1),
... SystemError(2),
... ExceptionGroup("group2",
... [OSError(3), RecursionError(4)])])
...
>>> try:
... f()
... except* OSError as e:
... print("There were OSErrors")
... except* SystemError as e:
... print("There were SystemErrors")
...
There were OSErrors
There were SystemErrors
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| File "<stdin>", line 2, in f
| ExceptionGroup: group1
+-+---------------- 1 ----------------
| ExceptionGroup: group2
+-+---------------- 1 ----------------
| RecursionError: 4
+------------------------------------
>>>
Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern:
>>>
>>> excs = []
... for test in tests:
... try:
... test.run()
... except Exception as e:
... excs.append(e)
...
>>> if excs:
... raise ExceptionGroup("Test Failures", excs)
...
8.10.?Enriching Exceptions with Notes
When an exception is created in order to be raised, it is usually initialized with information that describes the error that has occurred. There are cases where it is useful to add information after the exception was caught. For this purpose, exceptions have a method?add_note(note) ?that accepts a string and adds it to the exception's notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception.
>>>
>>> try:
... raise TypeError('bad type')
... except Exception as e:
... e.add_note('Add some information')
... e.add_note('Add some more information')
... raise
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: bad type
Add some information
Add some more information
>>>
For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors. In the following each exception in the group has a note indicating when this error has occurred.
>>>
>>> def f():
... raise OSError('operation failed')
...
>>> excs = []
>>> for i in range(3):
... try:
... f()
... except Exception as e:
... e.add_note(f'Happened in Iteration {i+1}')
... excs.append(e)
...
>>> raise ExceptionGroup('We have some problems', excs)
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ExceptionGroup: We have some problems (3 sub-exceptions)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in <module>
| File "<stdin>", line 2, in f
| OSError: operation failed
| Happened in Iteration 1
+---------------- 2 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in <module>
| File "<stdin>", line 2, in f
| OSError: operation failed
| Happened in Iteration 2
+---------------- 3 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in <module>
| File "<stdin>", line 2, in f
| OSError: operation failed
| Happened in Iteration 3
+------------------------------------
>>>
?
9.?Àà
Àà°ÑÊý¾ÝÓ빦ÄÜ°ó¶¨ÔÚÒ»Æð¡£´´½¨ÐÂÀà¾ÍÊÇ´´½¨ÐµĶÔÏó?ÀàÐÍ,´Ó¶ø´´½¨¸ÃÀàÐ͵ÄÐÂ?ʵÀý?¡£ÀàʵÀýÖ§³Öά³Ö×ÔÉí״̬µÄÊôÐÔ,»¹Ö§³Ö(ÓÉÀඨÒåµÄ)ÐÞ¸Ä×ÔÉí״̬µÄ·½·¨¡£
ºÍÆäËû±à³ÌÓïÑÔÏà±È,Python µÄÀàֻʹÓÃÁ˺ÜÉÙµÄÐÂÓï·¨ºÍÓïÒå¡£Python µÄÀàÓеãÀàËÆÓÚ C++ ºÍ Modula-3 ÖÐÀàµÄ½áºÏÌå,¶øÇÒÖ§³ÖÃæÏò¶ÔÏó±à³Ì(OOP)µÄËùÓбê×¼ÌØÐÔ:ÀàµÄ¼Ì³Ð»úÖÆÖ§³Ö¶à¸ö»ùÀà¡¢ÅÉÉúµÄÀàÄܸ²¸Ç»ùÀàµÄ·½·¨¡¢ÀàµÄ·½·¨Äܵ÷ÓûùÀàÖеÄͬÃû·½·¨¡£¶ÔÏó¿É°üº¬ÈÎÒâÊýÁ¿ºÍÀàÐ͵ÄÊý¾Ý¡£ºÍÄ£¿éÒ»Ñù,ÀàÒ²Ö§³Ö Python ¶¯Ì¬ÌØÐÔ:ÔÚÔËÐÐʱ´´½¨,´´½¨ºó»¹¿ÉÒÔÐ޸ġ£
Èç¹ûÓà C++ ÊõÓïÀ´ÃèÊöµÄ»°,Àà³ÉÔ±(°üÀ¨Êý¾Ý³ÉÔ±)ͨ³£Îª?public?(ÀýÍâµÄÇé¿ö¼ûÏÂÎÄ?˽ÓбäÁ¿),ËùÓгÉÔ±º¯Êý¶¼ÊÇ?virtual¡£ÓëÔÚ Modula-3 ÖÐÒ»Ñù,ûÓÐÓÃÓÚ´Ó¶ÔÏóµÄ·½·¨ÖÐÒýÓöÔÏó³ÉÔ±µÄ¼òдÐÎʽ:·½·¨º¯ÊýÔÚÉùÃ÷ʱ,ÓÐÒ»¸öÏÔʽµÄ²ÎÊý´ú±í±¾¶ÔÏó,¸Ã²ÎÊýÓɵ÷ÓÃÒþʽÌṩ¡£ ÓëÔÚ Smalltalk ÖÐÒ»Ñù,Python µÄÀàÒ²ÊǶÔÏó,ÕâΪµ¼ÈëºÍÖØÃüÃûÌṩÁËÓïÒåÖ§³Ö¡£Óë C++ ºÍ Modula-3 ²»Í¬,Python µÄÄÚÖÃÀàÐÍ¿ÉÒÔÓÃ×÷»ùÀà,¹©Óû§À©Õ¹¡£ ´ËÍâ,Óë C++ Ò»Ñù,ËãÊõÔËËã·û¡¢Ï±êµÈ¾ßÓÐÌØÊâÓï·¨µÄÄÚÖÃÔËËã·û¶¼¿ÉÒÔΪÀàʵÀý¶øÖØж¨Òå¡£
ÓÉÓÚȱ·¦¹ØÓÚÀàµÄ¹«ÈÏÊõÓï,±¾ÕÂÖÐż¶û»áʹÓà Smalltalk ºÍ C++ µÄÊõÓï¡£±¾Õ»¹»áʹÓà Modula-3 µÄÊõÓï,Modula-3 µÄÃæÏò¶ÔÏóÓïÒå±È C++ ¸ü½Ó½ü Python,µ«¹À¼ÆÌý˵¹ýÕâÃÅÓïÑԵĶÁÕߺÜÉÙ¡£
9.1.?Ãû³ÆºÍ¶ÔÏó
¶ÔÏóÖ®¼äÏ໥¶ÀÁ¢,¶à¸öÃû³Æ(ÔÚ¶à¸ö×÷ÓÃÓòÄÚ)¿ÉÒ԰󶨵½Í¬Ò»¸ö¶ÔÏó¡£ ÆäËûÓïÑÔ³Æ֮Ϊ±ðÃû¡£Python ³õѧÕßͨ³£²»ÈÝÒ×Àí½âÕâ¸ö¸ÅÄî,´¦ÀíÊý×Ö¡¢×Ö·û´®¡¢Ôª×éµÈ²»¿É±ä»ù±¾ÀàÐÍʱ,¿ÉÒÔ²»±ØÀí»á¡£ µ«ÊÇ,¶ÔÉæ¼°¿É±ä¶ÔÏó,ÈçÁÐ±í¡¢×ÖµäµÈ´ó¶àÊýÆäËûÀàÐ굀 Python ´úÂëµÄÓïÒå,±ðÃû¿ÉÄÜ»á²úÉúÒâÁÏÖ®ÍâµÄЧ¹û¡£ÕâÑù×ö,ͨ³£ÊÇΪÁËÈóÌÐòÊÜÒæ,ÒòΪ±ðÃûÔÚijЩ·½Ãæ¾ÍÏñÖ¸Õë¡£ÀýÈç,´«µÝ¶ÔÏóµÄ´ú¼ÛºÜС,ÒòΪʵÏÖÖ»´«µÝÒ»¸öÖ¸Õë;Èç¹ûº¯ÊýÐÞ¸ÄÁË×÷Ϊ²ÎÊý´«µÝµÄ¶ÔÏó,µ÷ÓÃÕ߾ͿÉÒÔ¿´µ½¸ü¸Ä --- ÎÞÐè Pascal ÓÃÁ½¸ö²»Í¬²ÎÊýµÄ´«µÝ»úÖÆ¡£
9.2.?Python ×÷ÓÃÓòºÍÃüÃû¿Õ¼ä
ÔÚ½éÉÜÀàÇ°,Ê×ÏÈÒª½éÉÜ Python µÄ×÷ÓÃÓò¹æÔò¡£ÀඨÒå¶ÔÃüÃû¿Õ¼äÓÐһЩÇÉÃîµÄ¼¼ÇÉ,Á˽â×÷ÓÃÓòºÍÃüÃû¿Õ¼äµÄ¹¤×÷»úÖÆÓÐÀûÓÚ¼ÓÇ¿¶ÔÀàµÄÀí½â¡£²¢ÇÒ,¼´±ã¶ÔÓڸ߼¶ Python ³ÌÐòÔ±,Õâ·½ÃæµÄ֪ʶҲºÜÓÐÓá£
½ÓÏÂÀ´,ÎÒÃÇÏÈÁ˽âһЩ¶¨Òå¡£
namespace?(ÃüÃû¿Õ¼ä)ÊÇÓ³Éäµ½¶ÔÏóµÄÃû³Æ¡£ÏÖÔÚ,´ó¶àÊýÃüÃû¿Õ¼ä¶¼Ê¹Óà Python ×ÖµäʵÏÖ,µ«³ý·ÇÉæ¼°µ½ÓÅ»¯ÐÔÄÜ,ÎÒÃÇÒ»°ã²»»á¹Ø×¢Õâ·½ÃæµÄÊÂÇé,¶øÇÒ½«À´Ò²¿ÉÄÜ»á¸Ä±äÕâÖÖ·½Ê½¡£ÃüÃû¿Õ¼äµÄ¼¸¸ö³£¼ûʾÀý:?abs()?º¯Êý¡¢ÄÚÖÃÒì³£µÈµÄÄÚÖú¯Êý¼¯ºÏ;Ä£¿éÖеÄÈ«¾ÖÃû³Æ;º¯Êýµ÷ÓÃÖеľֲ¿Ãû³Æ¡£¶ÔÏóµÄÊôÐÔ¼¯ºÏÒ²ËãÊÇÒ»ÖÖÃüÃû¿Õ¼ä¡£¹ØÓÚÃüÃû¿Õ¼äµÄÒ»¸öÖØҪ֪ʶµãÊÇ,²»Í¬ÃüÃû¿Õ¼äÖеÄÃû³ÆÖ®¼ä¾ø¶ÔûÓйØϵ;ÀýÈç,Á½¸ö²»Í¬µÄÄ£¿é¶¼¿ÉÒÔ¶¨Òå?maximize ?º¯Êý,ÇÒ²»»áÔì³É»ìÏý¡£Óû§Ê¹Óú¯Êýʱ±ØÐëÒªÔÚº¯ÊýÃûÇ°Ã渽¼ÓÉÏÄ£¿éÃû¡£
µãºÅÖ®ºóµÄÃû³ÆÊÇ?ÊôÐÔ¡£ÀýÈç,±í´ïʽ?z.real ?ÖÐ,real ?ÊǶÔÏó?z ?µÄÊôÐÔ¡£ÑϸñÀ´Ëµ,¶ÔÄ£¿éÖÐÃû³ÆµÄÒýÓÃÊÇÊôÐÔÒýÓÃ:±í´ïʽ?modname.funcname ?ÖÐ,modname ?ÊÇÄ£¿é¶ÔÏó,funcname ?ÊÇÄ£¿éµÄÊôÐÔ¡£Ä£¿éÊôÐÔºÍÄ£¿éÖж¨ÒåµÄÈ«¾ÖÃû³ÆÖ®¼ä´æÔÚÖ±½ÓµÄÓ³Éä:ËüÃǹ²ÏíÏàͬµÄÃüÃû¿Õ¼ä!?1
ÊôÐÔ¿ÉÒÔÊÇÖ»¶Á»òÕß¿ÉдµÄ¡£Èç¹û¿Éд,Ôò¿É¶ÔÊôÐÔ¸³Öµ¡£Ä£¿éÊôÐÔÊÇ¿Éдʱ,¿ÉÒÔʹÓÃ?modname.the_answer?=?42 ?¡£del?Óï¾ä¿ÉÒÔɾ³ý¿ÉдÊôÐÔ¡£ÀýÈç,?del?modname.the_answer ?»áɾ³ý?modname ?¶ÔÏóÖеÄ?the_answer ?ÊôÐÔ¡£
ÃüÃû¿Õ¼äÊÇÔÚ²»Í¬Ê±¿Ì´´½¨µÄ,ÇÒÓµÓв»Í¬µÄÉúÃüÖÜÆÚ¡£ÄÚÖÃÃû³ÆµÄÃüÃû¿Õ¼äÊÇÔÚ Python ½âÊÍÆ÷Æô¶¯Ê±´´½¨µÄ,ÓÀÔ¶²»»á±»É¾³ý¡£Ä£¿éµÄÈ«¾ÖÃüÃû¿Õ¼äÔÚ¶ÁÈ¡Ä£¿é¶¨Òåʱ´´½¨;ͨ³£,Ä£¿éµÄÃüÃû¿Õ¼äÒ²»á³ÖÐøµ½½âÊÍÆ÷Í˳ö¡£´Ó½Å±¾Îļþ¶ÁÈ¡»ò½»»¥Ê½¶ÁÈ¡µÄ,ÓɽâÊÍÆ÷¶¥²ãµ÷ÓÃÖ´ÐеÄÓï¾äÊÇ?__main__?Ä£¿éµ÷ÓõÄÒ»²¿·Ö,Ò²ÓµÓÐ×Ô¼ºµÄÈ«¾ÖÃüÃû¿Õ¼ä¡£ÄÚÖÃÃû³Æʵ¼ÊÉÏÒ²ÔÚÄ£¿éÀï,¼´?builtins?¡£
º¯ÊýµÄ±¾µØÃüÃû¿Õ¼äÔÚµ÷Óøú¯Êýʱ´´½¨,²¢ÔÚº¯Êý·µ»Ø»òÅ׳ö²»ÔÚº¯ÊýÄÚ²¿´¦ÀíµÄ´íÎóʱ±»É¾³ý¡£ (ʵ¼ÊÉÏ,Óá°ÒÅÍü¡±À´ÃèÊöʵ¼Ê·¢ÉúµÄÇé¿ö»á¸üºÃһЩ¡£) µ±È»,ÿ´ÎµÝ¹éµ÷Óö¼»áÓÐ×Ô¼ºµÄ±¾µØÃüÃû¿Õ¼ä¡£
×÷ÓÃÓò?ÊÇÃüÃû¿Õ¼ä¿ÉÖ±½Ó·ÃÎ浀 Python ³ÌÐòµÄÎı¾ÇøÓò¡£ ¡°¿ÉÖ±½Ó·ÃÎÊ¡± µÄÒâ˼ÊÇ,¶ÔÃû³ÆµÄ·ÇÏÞ¶¨ÒýÓûáÔÚÃüÃû¿Õ¼äÖвéÕÒÃû³Æ¡£
×÷ÓÃÓòËäÈ»ÊǾ²Ì¬È·¶¨µÄ,µ«»á±»¶¯Ì¬Ê¹Óá£Ö´ÐÐÆÚ¼äµÄÈκÎʱ¿Ì,¶¼»áÓÐ 3 »ò 4 ¸öÃüÃû¿Õ¼ä¿É±»Ö±½Ó·ÃÎʵÄǶÌ××÷ÓÃÓò:
-
×îÄÚ²ã×÷ÓÃÓò,°üº¬¾Ö²¿Ãû³Æ,²¢Ê×ÏÈÔÚÆäÖнøÐÐËÑË÷ -
·â±Õº¯ÊýµÄ×÷ÓÃÓò,°üº¬·Ç¾Ö²¿Ãû³ÆºÍ·ÇÈ«¾ÖÃû³Æ,´Ó×î½üµÄ·â±Õ×÷ÓÃÓò¿ªÊ¼ËÑË÷ -
µ¹ÊýµÚ¶þ¸ö×÷ÓÃÓò,°üº¬µ±Ç°Ä£¿éµÄÈ«¾ÖÃû³Æ -
×îÍâ²ãµÄ×÷ÓÃÓò,°üº¬ÄÚÖÃÃû³ÆµÄÃüÃû¿Õ¼ä,×îºóËÑË÷
Èç¹û°ÑÃû³ÆÉùÃ÷Ϊȫ¾Ö±äÁ¿,ÔòËùÓÐÒýÓú͸³Öµ½«Ö±½ÓÖ¸Ïò°üº¬¸ÃÄ£¿éµÄÈ«¾ÖÃû³ÆµÄÖмä×÷ÓÃÓò¡£ÖØаó¶¨ÔÚ×îÄÚ²ã×÷ÓÃÓòÒÔÍâÕÒµ½µÄ±äÁ¿,ʹÓÃ?nonlocal?Óï¾ä°Ñ¸Ã±äÁ¿ÉùÃ÷Ϊ·Ç¾Ö²¿±äÁ¿¡£Î´ÉùÃ÷Ϊ·Ç¾Ö²¿±äÁ¿µÄ±äÁ¿ÊÇÖ»¶ÁµÄ,(дÈëÖ»¶Á±äÁ¿»áÔÚ×îÄÚ²ã×÷ÓÃÓòÖд´½¨Ò»¸ö?еÄ?¾Ö²¿±äÁ¿,¶øͬÃûµÄÍⲿ±äÁ¿±£³Ö²»±ä¡£)
ͨ³£,µ±Ç°¾Ö²¿×÷ÓÃÓò½«(°´×ÖÃæÎı¾)ÒýÓõ±Ç°º¯ÊýµÄ¾Ö²¿Ãû³Æ¡£ÔÚº¯ÊýÖ®Íâ,¾Ö²¿×÷ÓÃÓòÒýÓÃÓëÈ«¾Ö×÷ÓÃÓòÒ»ÖµÄÃüÃû¿Õ¼ä:Ä£¿éµÄÃüÃû¿Õ¼ä¡£ ÀඨÒåÔÚ¾Ö²¿ÃüÃû¿Õ¼äÄÚÔÙ·ÅÖÃÁíÒ»¸öÃüÃû¿Õ¼ä¡£
»®Öصã,×÷ÓÃÓòÊÇ°´×ÖÃæÎı¾È·¶¨µÄ:Ä£¿éÄÚ¶¨ÒåµÄº¯ÊýµÄÈ«¾Ö×÷ÓÃÓò¾ÍÊǸÃÄ£¿éµÄÃüÃû¿Õ¼ä,ÎÞÂ۸ú¯Êý´ÓʲôµØ·½»òÒÔʲô±ðÃû±»µ÷Óá£ÁíÒ»·½Ãæ,ʵ¼ÊµÄÃû³ÆËÑË÷ÊÇÔÚÔËÐÐʱ¶¯Ì¬Íê³ÉµÄ¡£µ«ÊÇ,Python ÕýÔÚ³¯×Å¡°±àÒëʱ¾²Ì¬Ãû³Æ½âÎö¡±µÄ·½Ïò·¢Õ¹,Òò´Ë²»Òª¹ýÓÚÒÀÀµ¶¯Ì¬Ãû³Æ½âÎö!(¾Ö²¿±äÁ¿ÒѾÊDZ»¾²Ì¬È·¶¨ÁË¡£)
Python ÓÐÒ»¸öÌØÊâ¹æ¶¨¡£Èç¹û²»´æÔÚÉúЧµÄ?global?»ò?nonlocal?Óï¾ä,Ôò¶ÔÃû³ÆµÄ¸³Öµ×ÜÊÇ»á½øÈë×îÄÚ²ã×÷ÓÃÓò¡£¸³Öµ²»»á¸´ÖÆÊý¾Ý,Ö»Êǽ«Ãû³Æ°ó¶¨µ½¶ÔÏó¡£É¾³ýÒ²ÊÇÈç´Ë:Óï¾ä?del?x ?´Ó¾Ö²¿×÷ÓÃÓòÒýÓõÄÃüÃû¿Õ¼äÖÐÒƳý¶Ô?x ?µÄ°ó¶¨¡£ËùÓÐÒýÈëÐÂÃû³ÆµÄ²Ù×÷¶¼ÊÇʹÓþֲ¿×÷ÓÃÓò:ÓÈÆäÊÇ?import?Óï¾äºÍº¯Êý¶¨Òå»áÔÚ¾Ö²¿×÷ÓÃÓòÖаó¶¨Ä£¿é»òº¯ÊýÃû³Æ¡£
global?Óï¾äÓÃÓÚ±íÃ÷Ìض¨±äÁ¿ÔÚÈ«¾Ö×÷ÓÃÓòÀï,²¢Ó¦ÔÚÈ«¾Ö×÷ÓÃÓòÖÐÖØаó¶¨;nonlocal?Óï¾ä±íÃ÷Ìض¨±äÁ¿ÔÚÍâ²ã×÷ÓÃÓòÖÐ,²¢Ó¦ÔÚÍâ²ã×÷ÓÃÓòÖÐÖØа󶨡£
9.2.1.?×÷ÓÃÓòºÍÃüÃû¿Õ¼äʾÀý
ÏÂÀýÑÝʾÁËÈçºÎÒýÓò»Í¬×÷ÓÃÓòºÍÃû³Æ¿Õ¼ä,ÒÔ¼°?global?ºÍ?nonlocal?¶Ô±äÁ¿°ó¶¨µÄÓ°Ïì:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
ʾÀý´úÂëµÄÊä³öÊÇ:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
×¢Òâ,¾Ö²¿?¸³Öµ(ÕâÊÇĬÈÏ״̬)²»»á¸Ä±ä?scope_test?¶Ô?spam?µÄ°ó¶¨¡£?nonlocal?¸³Öµ»á¸Ä±ä?scope_test?¶Ô?spam?µÄ°ó¶¨,¶ø?global?¸³Öµ»á¸Ä±äÄ£¿é²ã¼¶µÄ°ó¶¨¡£
¶øÇÒ,global?¸³ÖµÇ°Ã»ÓÐ?spam?µÄ°ó¶¨¡£
9.3.?³õ̽Àà
ÀàÒýÈëÁËÒ»µãÐÂÓï·¨,ÈýÖÖеĶÔÏóÀàÐͺÍһЩÐÂÓïÒå¡£
9.3.1.?ÀඨÒåÓï·¨
×î¼òµ¥µÄÀඨÒåÐÎʽÈçÏÂ:
class ClassName:
<statement-1>
.
.
.
<statement-N>
Ó뺯Êý¶¨Òå (def?Óï¾ä) Ò»Ñù,ÀඨÒå±ØÐëÏÈÖ´ÐвÅÄÜÉúЧ¡£°ÑÀඨÒå·ÅÔÚ?if?Óï¾äµÄ·ÖÖ§Àï»òº¯ÊýÄÚ²¿ÊÔÊÔ¡£
ÔÚʵ¼ùÖÐ,ÀඨÒåÄÚµÄÓï¾äͨ³£¶¼ÊǺ¯Êý¶¨Òå,µ«Ò²¿ÉÒÔÊÇÆäËûÓï¾ä¡£Õⲿ·ÖÄÚÈÝÉÔºóÔÙÌÖÂÛ¡£ÀàÀïµÄº¯Êý¶¨ÒåÒ»°ãÊÇÌØÊâµÄ²ÎÊýÁбí,ÕâÊÇÓÉ·½·¨µ÷ÓõÄÔ¼¶¨¹æ·¶ËùÖ¸Ã÷µÄ --- ͬÑù,ÉÔºóÔÙ½âÊÍ¡£
µ±½øÈëÀඨÒåʱ,½«´´½¨Ò»¸öеÄÃüÃû¿Õ¼ä,²¢½«ÆäÓÃ×÷¾Ö²¿×÷ÓÃÓò --- Òò´Ë,ËùÓжԾֲ¿±äÁ¿µÄ¸³Öµ¶¼ÊÇÔÚÕâ¸öÐÂÃüÃû¿Õ¼äÖ®ÄÚ¡£ ÌرðµÄ,º¯Êý¶¨Òå»á°ó¶¨µ½ÕâÀïµÄк¯ÊýÃû³Æ¡£
µ±(´Ó½áβ´¦)Õý³£À뿪ÀඨÒåʱ,½«´´½¨Ò»¸ö?Àà¶ÔÏó¡£ Õâ»ù±¾ÉÏÊÇÒ»¸ö°üΧÔÚÀඨÒåËù´´½¨ÃüÃû¿Õ¼äÄÚÈÝÖÜΧµÄ°ü×°Æ÷;ÎÒÃǽ«ÔÚÏÂÒ»½ÚÁ˽âÓйØÀà¶ÔÏóµÄ¸ü¶àÐÅÏ¢¡£ ÔʼµÄ(ÔÚ½øÈëÀඨÒå֮ǰÆð×÷ÓõÄ)¾Ö²¿×÷ÓÃÓò½«ÖØÐÂÉúЧ,Àà¶ÔÏó½«ÔÚÕâÀï±»°ó¶¨µ½ÀඨÒåÍ·Ëù¸ø³öµÄÀàÃû³Æ (ÔÚÕâ¸öʾÀýÖÐΪ?ClassName )¡£
9.3.2.?Class ¶ÔÏó
Àà¶ÔÏóÖ§³ÖÁ½ÖÖ²Ù×÷:ÊôÐÔÒýÓúÍʵÀý»¯¡£
ÊôÐÔÒýÓÃ?ʹÓà Python ÖÐËùÓÐÊôÐÔÒýÓÃËùʹÓõıê×¼Óï·¨:?obj.name ¡£ ÓÐЧµÄÊôÐÔÃû³ÆÊÇÀà¶ÔÏó±»´´½¨Ê±´æÔÚÓÚÀàÃüÃû¿Õ¼äÖеÄËùÓÐÃû³Æ¡£ Òò´Ë,Èç¹ûÀඨÒåÊÇÕâÑùµÄ:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
ÄÇô?MyClass.i ?ºÍ?MyClass.f ?¾ÍÊÇÓÐЧµÄÊôÐÔÒýÓÃ,½«·Ö±ð·µ»ØÒ»¸öÕûÊýºÍÒ»¸öº¯Êý¶ÔÏó¡£ ÀàÊôÐÔÒ²¿ÉÒÔ±»¸³Öµ,Òò´Ë¿ÉÒÔͨ¹ý¸³ÖµÀ´¸ü¸Ä?MyClass.i ?µÄÖµ¡£?__doc__ ?Ò²ÊÇÒ»¸öÓÐЧµÄÊôÐÔ,½«·µ»ØËùÊôÀàµÄÎĵµ×Ö·û´®:?"A?simple?example?class" ¡£
ÀàµÄ?ʵÀý»¯?ʹÓú¯Êý±íʾ·¨¡£ ¿ÉÒÔ°ÑÀà¶ÔÏóÊÓΪÊÇ·µ»Ø¸ÃÀàµÄÒ»¸öÐÂʵÀýµÄ²»´ø²ÎÊýµÄº¯Êý¡£ ¾ÙÀýÀ´Ëµ(¼ÙÉèʹÓÃÉÏÊöµÄÀà):
x = MyClass()
´´½¨ÀàµÄÐÂ?ʵÀý?²¢½«´Ë¶ÔÏó·ÖÅä¸ø¾Ö²¿±äÁ¿?x ¡£
ʵÀý»¯²Ù×÷(¡°µ÷Óá±Àà¶ÔÏó)»á´´½¨Ò»¸ö¿Õ¶ÔÏó¡£ Ðí¶àÀàϲ»¶´´½¨´øÓÐÌض¨³õʼ״̬µÄ×Ô¶¨ÒåʵÀý¡£ Ϊ´ËÀඨÒå¿ÉÄÜ°üº¬Ò»¸öÃûΪ?__init__() ?µÄÌØÊâ·½·¨,¾ÍÏñÕâÑù:
def __init__(self):
self.data = []
µ±Ò»¸öÀඨÒåÁË?__init__() ?·½·¨Ê±,ÀàµÄʵÀý»¯²Ù×÷»á×Ô¶¯ÎªÐ´´½¨µÄÀàʵÀý·¢Æðµ÷ÓÃ?__init__() ¡£ Òò´ËÔÚÕâ¸öʾÀýÖÐ,¿ÉÒÔͨ¹ýÒÔÏÂÓï¾ä»ñµÃÒ»¸ö¾³õʼ»¯µÄÐÂʵÀý:
x = MyClass()
µ±È»,__init__() ?·½·¨»¹¿ÉÒÔÓжîÍâ²ÎÊýÒÔʵÏÖ¸ü¸ßÁé»îÐÔ¡£ ÔÚÕâÖÖÇé¿öÏÂ,Ìṩ¸øÀàʵÀý»¯ÔËËã·ûµÄ²ÎÊý½«±»´«µÝ¸ø?__init__() ¡£ ÀýÈç,:
>>>
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
9.3.3.?ʵÀý¶ÔÏó
ÏÖÔÚÎÒÃÇÄÜÓÃʵÀý¶ÔÏó×öʲô? ʵÀý¶ÔÏóËùÄÜÀí½âµÄΨһ²Ù×÷ÊÇÊôÐÔÒýÓᣠÓÐÁ½ÖÖÓÐЧµÄÊôÐÔÃû³Æ:Êý¾ÝÊôÐԺͷ½·¨¡£
Êý¾ÝÊôÐÔ?¶ÔÓ¦ÓÚ Smalltalk Öеġ°ÊµÀý±äÁ¿¡±,ÒÔ¼° C++ Öеġ°Êý¾Ý³ÉÔ±¡±¡£ Êý¾ÝÊôÐÔ²»ÐèÒªÉùÃ÷;Ïñ¾Ö²¿±äÁ¿Ò»Ñù,ËüÃǽ«ÔÚµÚÒ»´Î±»¸³ÖµÊ±²úÉú¡£ ÀýÈç,Èç¹û?x ?ÊÇÉÏÃæ´´½¨µÄ?MyClass ?µÄʵÀý,ÔòÒÔÏ´úÂë¶Î½«´òÓ¡ÊýÖµ?16 ,ÇÒ²»±£ÁôÈκÎ×·×ÙÐÅÏ¢:
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
ÁíÒ»ÀàʵÀýÊôÐÔÒýÓóÆΪ?·½·¨¡£ ·½·¨ÊÇ¡°´ÓÊôÓÚ¡±¶ÔÏóµÄº¯Êý¡£ (ÔÚ Python ÖÐ,·½·¨Õâ¸öÊõÓï²¢²»ÊÇÀàʵÀýËùÌØÓеÄ:ÆäËû¶ÔÏóÒ²¿ÉÒÔÓз½·¨¡£ ÀýÈç,Áбí¶ÔÏó¾ßÓÐ append, insert, remove, sort µÈ·½·¨¡£ È»¶ø,ÔÚÒÔÏÂÌÖÂÛÖÐ,ÎÒÃÇʹÓ÷½·¨Ò»´Ê½«×¨Ö¸ÀàʵÀý¶ÔÏóµÄ·½·¨,³ý·ÇÁíÍâÏÔʽµØ˵Ã÷¡£)
ʵÀý¶ÔÏóµÄÓÐЧ·½·¨Ãû³ÆÒÀÀµÓÚÆäËùÊôµÄÀà¡£ ¸ù¾Ý¶¨Òå,Ò»¸öÀàÖÐËùÓÐÊǺ¯Êý¶ÔÏóµÄÊôÐÔ¶¼ÊǶ¨ÒåÁËÆäʵÀýµÄÏàÓ¦·½·¨¡£ Òò´ËÔÚÎÒÃǵÄʾÀýÖÐ,x.f ?ÊÇÓÐЧµÄ·½·¨ÒýÓÃ,ÒòΪ?MyClass.f ?ÊÇÒ»¸öº¯Êý,¶ø?x.i ?²»ÊÇ·½·¨,ÒòΪ?MyClass.i ?²»ÊǺ¯Êý¡£ µ«ÊÇ?x.f ?Óë?MyClass.f ?²¢²»ÊÇÒ»»ØÊ --- ËüÊÇÒ»¸ö?·½·¨¶ÔÏó,²»ÊǺ¯Êý¶ÔÏó¡£
9.3.4.?·½·¨¶ÔÏó
ͨ³£,·½·¨Ôڰ󶨺óÁ¢¼´±»µ÷ÓÃ:
x.f()
ÔÚ?MyClass ?ʾÀýÖÐ,Õ⽫·µ»Ø×Ö·û´®?'hello?world' ¡£ µ«ÊÇ,Á¢¼´µ÷ÓÃÒ»¸ö·½·¨²¢²»ÊDZØÐëµÄ:?x.f ?ÊÇÒ»¸ö·½·¨¶ÔÏó,Ëü¿ÉÒÔ±»±£´æÆðÀ´ÒÔºóÔÙµ÷ÓᣠÀýÈç:
xf = x.f
while True:
print(xf())
½«³ÖÐø´òÓ¡?hello?world ,Ö±µ½½áÊø¡£
µ±Ò»¸ö·½·¨±»µ÷ÓÃʱµ½µ×·¢ÉúÁËʲô? Äã¿ÉÄÜÒѾעÒâµ½ÉÏÃæµ÷ÓÃ?x.f() ?ʱ²¢Ã»Óдø²ÎÊý,ËäÈ»?f() ?µÄº¯Êý¶¨ÒåÖ¸¶¨ÁËÒ»¸ö²ÎÊý¡£ Õâ¸ö²ÎÊý·¢ÉúÁËʲôÊÂ? µ±²»´ø²ÎÊýµØµ÷ÓÃÒ»¸öÐèÒª²ÎÊýµÄº¯Êýʱ Python ¿Ï¶¨»áÒý·¢Òì³£ --- ¼´Ê¹²ÎÊýʵ¼Êδ±»Ê¹ÓÃ...
ʵ¼ÊÉÏ,Äã¿ÉÄÜÒѾ²Âµ½ÁË´ð°¸:·½·¨µÄÌØÊâÖ®´¦¾ÍÔÚÓÚʵÀý¶ÔÏó»á×÷Ϊº¯ÊýµÄµÚÒ»¸ö²ÎÊý±»´«Èë¡£ ÔÚÎÒÃǵÄʾÀýÖÐ,µ÷ÓÃ?x.f() ?Æäʵ¾ÍÏ൱ÓÚ?MyClass.f(x) ¡£ ×ÜÖ®,µ÷ÓÃÒ»¸ö¾ßÓÐ?n?¸ö²ÎÊýµÄ·½·¨¾ÍÏ൱ÓÚµ÷ÓÃÔÙ¶àÒ»¸ö²ÎÊýµÄ¶ÔÓ¦º¯Êý,Õâ¸ö²ÎÊýֵΪ·½·¨ËùÊôʵÀý¶ÔÏó,λÖÃÔÚÆäËû²ÎÊý֮ǰ¡£
Èç¹ûÄãÈÔÈ»ÎÞ·¨Àí½â·½·¨µÄÔË×÷ÔÀí,ÄÇô²é¿´ÊµÏÖϸ½Ú¿ÉÄÜ»áŪÇå³þÎÊÌâ¡£ µ±Ò»¸öʵÀýµÄ·ÇÊý¾ÝÊôÐÔ±»ÒýÓÃʱ,½«ËÑË÷ʵÀýËùÊôµÄÀà¡£ Èç¹û±»ÒýÓõÄÊôÐÔÃû³Æ±íʾһ¸öÓÐЧµÄÀàÊôÐÔÖеĺ¯Êý¶ÔÏó,»áͨ¹ý´ò°ü(Ö¸Ïò)²éÕÒµ½µÄʵÀý¶ÔÏóºÍº¯Êý¶ÔÏóµ½Ò»¸ö³éÏó¶ÔÏóµÄ·½Ê½À´´´½¨·½·¨¶ÔÏó:Õâ¸ö³éÏó¶ÔÏó¾ÍÊÇ·½·¨¶ÔÏó¡£ µ±¸½´ø²ÎÊýÁбíµ÷Ó÷½·¨¶ÔÏóʱ,½«»ùÓÚʵÀý¶ÔÏóºÍ²ÎÊýÁÐ±í¹¹½¨Ò»¸öеIJÎÊýÁбí,²¢Ê¹ÓÃÕâ¸öвÎÊýÁбíµ÷ÓÃÏàÓ¦µÄº¯Êý¶ÔÏó¡£
9.3.5.?ÀàºÍʵÀý±äÁ¿
Ò»°ãÀ´Ëµ,ʵÀý±äÁ¿ÓÃÓÚÿ¸öʵÀýµÄΨһÊý¾Ý,¶øÀà±äÁ¿ÓÃÓÚÀàµÄËùÓÐʵÀý¹²ÏíµÄÊôÐԺͷ½·¨:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
ÕýÈç?Ãû³ÆºÍ¶ÔÏó?ÖÐÒÑÌÖÂÛ¹ýµÄ,¹²ÏíÊý¾Ý¿ÉÄÜÔÚÉæ¼°?mutable?¶ÔÏóÀýÈçÁбíºÍ×ÖµäµÄʱºòµ¼ÖÂÁîÈ˾ªÑȵĽá¹û¡£ ÀýÈçÒÔÏ´úÂëÖеÄ?tricks?ÁÐ±í²»Ó¦¸Ã±»ÓÃ×÷Àà±äÁ¿,ÒòΪËùÓеÄ?Dog?ʵÀý½«Ö»¹²ÏíÒ»¸öµ¥¶ÀµÄÁбí:
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks # unexpectedly shared by all dogs
['roll over', 'play dead']
ÕýÈ·µÄÀàÉè¼ÆÓ¦¸ÃʹÓÃʵÀý±äÁ¿:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']
9.4.?²¹³ä˵Ã÷
Èç¹ûͬÑùµÄÊôÐÔÃû³Æͬʱ³öÏÖÔÚʵÀýºÍÀàÖÐ,ÔòÊôÐÔ²éÕÒ»áÓÅÏÈÑ¡ÔñʵÀý:
>>>
>>> class Warehouse:
... purpose = 'storage'
... region = 'west'
...
>>> w1 = Warehouse()
>>> print(w1.purpose, w1.region)
storage west
>>> w2 = Warehouse()
>>> w2.region = 'east'
>>> print(w2.purpose, w2.region)
storage east
Êý¾ÝÊôÐÔ¿ÉÒÔ±»·½·¨ÒÔ¼°Ò»¸ö¶ÔÏóµÄÆÕͨÓû§(¡°¿Í»§¶Ë¡±)ËùÒýÓᣠ»»¾ä»°Ëµ,À಻ÄÜÓÃÓÚʵÏÖ´¿³éÏóÊý¾ÝÀàÐÍ¡£ ʵ¼ÊÉÏ,ÔÚ Python ÖÐûÓÐÈκζ«Î÷ÄÜÇ¿ÖÆÒþ²ØÊý¾Ý --- ËüÊÇÍêÈ«»ùÓÚÔ¼¶¨µÄ¡£ (¶øÔÚÁíÒ»·½Ãæ,Óà C ÓïÑÔ±àдµÄ Python ʵÏÖÔò¿ÉÒÔÍêÈ«Òþ²ØʵÏÖϸ½Ú,²¢ÔÚ±ØҪʱ¿ØÖƶÔÏóµÄ·ÃÎÊ;´ËÌØÐÔ¿ÉÒÔͨ¹ýÓà C ±àд Python À©Õ¹À´Ê¹Óá£)
¿Í»§¶ËÓ¦µ±½÷É÷µØʹÓÃÊý¾ÝÊôÐÔ --- ¿Í»§¶Ë¿ÉÄÜͨ¹ýÖ±½Ó²Ù×÷Êý¾ÝÊôÐԵķ½Ê½ÆÆ»µÓÉ·½·¨Ëùά»¤µÄ¹Ì¶¨±äÁ¿¡£ Çë×¢Òâ¿Í»§¶Ë¿ÉÒÔÏòÒ»¸öʵÀý¶ÔÏóÌí¼ÓËûÃÇ×Ô¼ºµÄÊý¾ÝÊôÐÔ¶ø²»»áÓ°Ïì·½·¨µÄ¿ÉÓÃÐÔ,Ö»Òª±£Ö¤±ÜÃâÃû³Æ³åÍ» --- ÔÙ´ÎÌáÐÑ,ÔÚ´ËʹÓÃÃüÃûÔ¼¶¨¿ÉÒÔÊ¡È¥Ðí¶àÁîÈËÍ·Í´µÄÂé·³¡£
ÔÚ·½·¨ÄÚ²¿ÒýÓÃÊý¾ÝÊôÐÔ(»òÆäËû·½·¨!)²¢Ã»Óмò±ã·½Ê½¡£ ÎÒ·¢ÏÖÕâʵ¼ÊÉÏÌáÉýÁË·½·¨µÄ¿É¶ÁÐÔ:µ±ä¯ÀÀÒ»¸ö·½·¨´úÂëʱ,²»»á´æÔÚ»ìÏý¾Ö²¿±äÁ¿ºÍʵÀý±äÁ¿µÄ»ú»á¡£
·½·¨µÄµÚÒ»¸ö²ÎÊý³£³£±»ÃüÃûΪ?self ¡£ ÕâÒ²²»¹ý¾ÍÊÇÒ»¸öÔ¼¶¨:?self ?ÕâÒ»Ãû³ÆÔÚ Python Öоø¶ÔûÓÐÌØÊ⺬Òå¡£ µ«ÊÇҪעÒâ,²»×ñÑ´ËÔ¼¶¨»áʹµÃÄãµÄ´úÂë¶ÔÆäËû Python ³ÌÐòÔ±À´ËµÈ±·¦¿É¶ÁÐÔ,¶øÇÒÒ²¿ÉÒÔÏëÏñÒ»¸ö?Ààä¯ÀÀÆ÷?³ÌÐòµÄ±àд¿ÉÄÜ»áÒÀÀµÓÚÕâÑùµÄÔ¼¶¨¡£
ÈκÎÒ»¸ö×÷ΪÀàÊôÐԵĺ¯Êý¶¼Îª¸ÃÀàµÄʵÀý¶¨ÒåÁËÒ»¸öÏàÓ¦·½·¨¡£ º¯Êý¶¨ÒåµÄÎı¾²¢·Ç±ØÐë°üº¬ÓÚÀඨÒåÖ®ÄÚ:½«Ò»¸öº¯Êý¶ÔÏó¸³Öµ¸øÒ»¸ö¾Ö²¿±äÁ¿Ò²ÊÇ¿ÉÒԵġ£ ÀýÈç:
# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return 'hello world'
h = g
ÏÖÔÚ?f ,?g ?ºÍ?h ?¶¼ÊÇ?C ?ÀàµÄÒýÓú¯Êý¶ÔÏóµÄÊôÐÔ,Òò¶øËüÃǾͶ¼ÊÇ?C ?µÄʵÀýµÄ·½·¨ --- ÆäÖÐ?h ?ÍêÈ«µÈͬÓÚ?g ¡£ µ«Çë×¢Òâ,±¾Ê¾ÀýµÄ×ö·¨Í¨³£Ö»»áÁî³ÌÐòµÄÔĶÁÕ߸е½ÃÔ»ó¡£
·½·¨¿ÉÒÔͨ¹ýʹÓÃ?self ?²ÎÊýµÄ·½·¨ÊôÐÔµ÷ÓÃÆäËû·½·¨:
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
·½·¨¿ÉÒÔͨ¹ýÓëÆÕͨº¯ÊýÏàͬµÄ·½Ê½ÒýÓÃÈ«¾ÖÃû³Æ¡£ Óë·½·¨Ïà¹ØÁªµÄÈ«¾Ö×÷ÓÃÓò¾ÍÊÇ°üº¬Æ䶨ÒåµÄÄ£¿é¡£ (ÀàÓÀÔ¶²»»á±»×÷Ϊȫ¾Ö×÷ÓÃÓò¡£) ËäÈ»ÎÒÃǺÜÉÙ»áÓгä·ÖµÄÀíÓÉÔÚ·½·¨ÖÐʹÓÃÈ«¾Ö×÷ÓÃÓò,µ«È«¾Ö×÷ÓÃÓò´æÔÚÐí¶àºÏÀíµÄʹÓó¡¾°:¾Ù¸öÀý×Ó,µ¼È뵽ȫ¾Ö×÷ÓÃÓòµÄº¯ÊýºÍÄ£¿é¿ÉÒÔ±»·½·¨ËùʹÓÃ,ÔÚÆäÖж¨ÒåµÄº¯ÊýºÍÀàÒ²Ò»Ñù¡£ ͨ³£,°üº¬¸Ã·½·¨µÄÀà±¾ÉíÊÇÔÚÈ«¾Ö×÷ÓÃÓòÖж¨ÒåµÄ,¶øÔÚÏÂÒ»½ÚÖÐÎÒÃǽ«»á·¢ÏÖΪºÎ·½·¨ÐèÒªÒýÓÃÆäËùÊôÀàµÄºÜºÃµÄÀíÓÉ¡£
ÿ¸öÖµ¶¼ÊÇÒ»¸ö¶ÔÏó,Òò´Ë¾ßÓÐ?Àà?(Ò²³ÆΪ?ÀàÐÍ),²¢´æ´¢Îª?object.__class__ ?¡£
9.5.?¼Ì³Ð
µ±È»,Èç¹û²»Ö§³Ö¼Ì³Ð,ÓïÑÔÌØÐԾͲ»ÖµµÃ³ÆΪ¡°Àࡱ¡£ÅÉÉúÀඨÒåµÄÓï·¨ÈçÏÂËùʾ:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
Ãû³Æ?BaseClassName ?±ØÐ붨ÒåÓÚ°üº¬ÅÉÉúÀඨÒåµÄ×÷ÓÃÓòÖС£ Ò²ÔÊÐíÓÃÆäËûÈÎÒâ±í´ïʽ´úÌæ»ùÀàÃû³ÆËùÔÚµÄλÖᣠÕâÓÐʱҲ¿ÉÄÜ»áÓõÃÉÏ,ÀýÈç,µ±»ùÀඨÒåÔÚÁíÒ»¸öÄ£¿éÖеÄʱºò:
class DerivedClassName(modname.BaseClassName):
ÅÉÉúÀඨÒåµÄÖ´Ðйý³ÌÓë»ùÀàÏàͬ¡£ µ±¹¹ÔìÀà¶ÔÏóʱ,»ùÀà»á±»¼Çס¡£ ´ËÐÅÏ¢½«±»ÓÃÀ´½âÎöÊôÐÔÒýÓÃ:Èç¹ûÇëÇóµÄÊôÐÔÔÚÀàÖÐÕÒ²»µ½,ËÑË÷½«×ªÍù»ùÀàÖнøÐвéÕÒ¡£ Èç¹û»ùÀà±¾ÉíÒ²ÅÉÉú×ÔÆäËûij¸öÀà,Ôò´Ë¹æÔò½«±»µÝ¹éµØÓ¦Óá£
ÅÉÉúÀàµÄʵÀý»¯Ã»ÓÐÈκÎÌØÊâÖ®´¦:?DerivedClassName() ?»á´´½¨¸ÃÀàµÄÒ»¸öÐÂʵÀý¡£ ·½·¨ÒýÓý«°´ÒÔÏ·½Ê½½âÎö:ËÑË÷ÏàÓ¦µÄÀàÊôÐÔ,ÈçÓбØÒª½«°´»ùÀà¼Ì³ÐÁ´Öð²½ÏòϲéÕÒ,Èç¹û²úÉúÁËÒ»¸öº¯Êý¶ÔÏóÔò·½·¨ÒýÓþÍÉúЧ¡£
ÅÉÉúÀà¿ÉÄÜ»áÖØдÆä»ùÀàµÄ·½·¨¡£ ÒòΪ·½·¨ÔÚµ÷ÓÃͬһ¶ÔÏóµÄÆäËû·½·¨Ê±Ã»ÓÐÌØÊâȨÏÞ,ËùÒÔµ÷ÓÃͬһ»ùÀàÖж¨ÒåµÄÁíÒ»·½·¨µÄ»ùÀà·½·¨×îÖÕ¿ÉÄÜ»áµ÷Óø²¸ÇËüµÄÅÉÉúÀàµÄ·½·¨¡£ (¶Ô C++ ³ÌÐòÔ±µÄÌáʾ:Python ÖÐËùÓеķ½·¨Êµ¼ÊÉ϶¼ÊÇ?virtual ?·½·¨¡£)
ÔÚÅÉÉúÀàÖеÄÖØÔØ·½·¨Êµ¼ÊÉÏ¿ÉÄÜÏëÒªÀ©Õ¹¶ø·Ç¼òµ¥µØÌ滻ͬÃûµÄ»ùÀà·½·¨¡£ ÓÐÒ»ÖÖ·½Ê½¿ÉÒÔ¼òµ¥µØÖ±½Óµ÷ÓûùÀà·½·¨:¼´µ÷ÓÃ?BaseClassName.methodname(self,?arguments) ¡£ ÓÐʱÕâ¶Ô¿Í»§¶ËÀ´ËµÒ²ÊÇÓÐÓõġ£ (Çë×¢Òâ½öµ±´Ë»ùÀà¿ÉÔÚÈ«¾Ö×÷ÓÃÓòÖÐÒÔ?BaseClassName ?µÄÃû³Æ±»·ÃÎÊʱ·½¿ÉʹÓô˷½Ê½¡£)
PythonÓÐÁ½¸öÄÚÖú¯Êý¿É±»ÓÃÓڼ̳лúÖÆ:
-
ʹÓÃ?isinstance()?À´¼ì²éÒ»¸öʵÀýµÄÀàÐÍ:?isinstance(obj,?int) ?½ö»áÔÚ?obj.__class__ ?Ϊ?int?»òij¸öÅÉÉú×Ô?int?µÄÀàʱΪ?True ¡£ -
ʹÓÃ?issubclass()?À´¼ì²éÀàµÄ¼Ì³Ð¹Øϵ:?issubclass(bool,?int) ?Ϊ?True ,ÒòΪ?bool?ÊÇ?int?µÄ×ÓÀà¡£ µ«ÊÇ,issubclass(float,?int) ?Ϊ?False ,ÒòΪ?float?²»ÊÇ?int?µÄ×ÓÀà¡£
9.5.1.?¶àÖؼ̳Ð
Python Ò²Ö§³ÖÒ»ÖÖ¶àÖؼ̳С£ ´øÓжà¸ö»ùÀàµÄÀඨÒåÓï¾äÈçÏÂËùʾ:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
¶ÔÓÚ¶àÊýÓ¦ÓÃÀ´Ëµ,ÔÚ×î¼òµ¥µÄÇé¿öÏÂ,Äã¿ÉÒÔÈÏΪËÑË÷´Ó¸¸ÀàËù¼Ì³ÐÊôÐԵIJÙ×÷ÊÇÉî¶ÈÓÅÏÈ¡¢´Ó×óÖÁÓÒµÄ,µ±²ã´Î½á¹¹ÖдæÔÚÖصþʱ²»»áÔÚͬһ¸öÀàÖÐËÑË÷Á½´Î¡£ Òò´Ë,Èç¹ûijһÊôÐÔÔÚ?DerivedClassName ?ÖÐδÕÒµ½,Ôò»áµ½?Base1 ?ÖÐËÑË÷Ëü,È»ºó(µÝ¹éµØ)µ½?Base1 ?µÄ»ùÀàÖÐËÑË÷,Èç¹ûÔÚÄÇÀïδÕÒµ½,ÔÙµ½?Base2 ?ÖÐËÑË÷,ÒÀ´ËÀàÍÆ¡£
ÕæʵÇé¿ö±ÈÕâ¸ö¸ü¸´ÔÓһЩ;·½·¨½âÎö˳Ðò»á¶¯Ì¬¸Ä±äÒÔÖ§³Ö¶Ô?super()?µÄÐͬµ÷ÓᣠÕâÖÖ·½Ê½ÔÚijЩÆäËû¶àÖؼ̳ÐÐÍÓïÑÔÖб»³ÆΪºóÐø·½·¨µ÷ÓÃ,Ëü±Èµ¥¼Ì³ÐÐÍÓïÑÔÖÐµÄ super µ÷ÓøüÇ¿´ó¡£
¶¯Ì¬¸Ä±ä˳ÐòÊÇÓбØÒªµÄ,ÒòΪËùÓжàÖؼ̳еÄÇé¿ö¶¼»áÏÔʾ³öÒ»¸ö»ò¸ü¶àµÄÁâÐιØÁª(¼´ÖÁÉÙÓÐÒ»¸ö¸¸Àà¿Éͨ¹ý¶àÌõ·¾¶±»×îµ×²ãÀàËù·ÃÎÊ)¡£ ÀýÈç,ËùÓÐÀ඼ÊǼ̳Ð×Ô?object,Òò´ËÈκζàÖؼ̳еÄÇé¿ö¶¼ÌṩÁËÒ»ÌõÒÔÉϵÄ·¾¶¿ÉÒÔͨÏò?object¡£ ΪÁËÈ·±£»ùÀ಻»á±»·ÃÎÊÒ»´ÎÒÔÉÏ,¶¯Ì¬Ëã·¨»áÓÃÒ»ÖÖÌØÊⷽʽ½«ËÑË÷˳ÐòÏßÐÔ»¯, ±£Áôÿ¸öÀàËùÖ¸¶¨µÄ´Ó×óÖÁÓÒµÄ˳Ðò,Ö»µ÷ÓÃÿ¸ö¸¸ÀàÒ»´Î,²¢ÇÒ±£³Öµ¥µ÷(¼´Ò»¸öÀà¿ÉÒÔ±»×ÓÀ໯¶ø²»Ó°ÏìÆ丸ÀàµÄÓÅÏÈ˳Ðò)¡£ ×ܶøÑÔÖ®,ÕâЩÌØÐÔʹµÃÉè¼Æ¾ßÓжàÖؼ̳еĿɿ¿ÇÒ¿ÉÀ©Õ¹µÄÀà³ÉΪ¿ÉÄÜ¡£ ÒªÁ˽â¸ü¶àϸ½Ú,Çë²ÎÔÄ?The Python 2.3 Method Resolution Order | Python.org¡£
9.6.?˽ÓбäÁ¿
ÄÇÖÖ½öÏÞ´ÓÒ»¸ö¶ÔÏóÄÚ²¿·ÃÎʵġ°Ë½ÓС±ÊµÀý±äÁ¿ÔÚ Python Öв¢²»´æÔÚ¡£ µ«ÊÇ,´ó¶àÊý Python ´úÂ붼×ñÑÕâÑùÒ»¸öÔ¼¶¨:´øÓÐÒ»¸öÏ»®ÏßµÄÃû³Æ (ÀýÈç?_spam ) Ó¦¸Ã±»µ±×÷ÊÇ API µÄ·Ç¹«Óв¿·Ö (ÎÞÂÛËüÊǺ¯Êý¡¢·½·¨»òÊÇÊý¾Ý³ÉÔ±)¡£ ÕâÓ¦µ±±»ÊÓΪһ¸öʵÏÖϸ½Ú,¿ÉÄܲ»¾Í¨Öª¼´¼ÓÒԸı䡣
ÓÉÓÚ´æÔÚ¶ÔÓÚÀà˽ÓгÉÔ±µÄÓÐЧʹÓó¡¾°(ÀýÈç±ÜÃâÃû³ÆÓë×ÓÀàËù¶¨ÒåµÄÃû³ÆÏà³åÍ»),Òò´Ë´æÔÚ¶Ô´ËÖÖ»úÖƵÄÓÐÏÞÖ§³Ö,³ÆΪ?Ãû³Æ¸Äд¡£ ÈκÎÐÎʽΪ?__spam ?µÄ±êʶ·û(ÖÁÉÙ´øÓÐÁ½¸öǰ׺Ï»®Ïß,ÖÁ¶àÒ»¸öºó׺Ï»®Ïß)µÄÎı¾½«±»Ì滻Ϊ?_classname__spam ,ÆäÖÐ?classname ?Ϊȥ³ýÁËǰ׺Ï»®Ïߵĵ±Ç°ÀàÃû³Æ¡£ ÕâÖÖ¸Äд²»¿¼ÂDZêʶ·ûµÄ¾ä·¨Î»ÖÃ,Ö»ÒªËü³öÏÖÔÚÀඨÒåÄÚ²¿¾Í»á½øÐС£
Ãû³Æ¸ÄдÓÐÖúÓÚÈÃ×ÓÀàÖØÔØ·½·¨¶ø²»ÆÆ»µÀàÄÚ·½·¨µ÷Óá£ÀýÈç:
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # private copy of original update() method
class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
ÉÏÃæµÄʾÀý¼´Ê¹ÔÚ?MappingSubclass ?ÒýÈëÁËÒ»¸ö?__update ?±êʶ·ûµÄÇé¿öÏÂÒ²²»»á³ö´í,ÒòΪËü»áÔÚ?Mapping ?ÀàÖб»Ì滻Ϊ?_Mapping__update ?¶øÔÚ?MappingSubclass ?ÀàÖб»Ì滻Ϊ?_MappingSubclass__update ¡£
Çë×¢Òâ,¸Äд¹æÔòµÄÉè¼ÆÖ÷ÒªÊÇΪÁ˱ÜÃâÒâÍâ³åÍ»;·ÃÎÊ»òÐ޸ı»ÊÓΪ˽ÓеıäÁ¿ÈÔÈ»ÊÇ¿ÉÄܵġ£ÕâÔÚÌØÊâÇé¿öÏÂÉõÖÁ»áºÜÓÐÓÃ,ÀýÈçÔÚµ÷ÊÔÆ÷ÖС£
Çë×¢Òâ´«µÝ¸ø?exec() ?»ò?eval() ?µÄ´úÂë²»»á½«·¢Æðµ÷ÓÃÀàµÄÀàÃûÊÓ×÷µ±Ç°Àà;ÕâÀàËÆÓÚ?global ?Óï¾äµÄЧ¹û,Òò´ËÕâÖÖЧ¹û½öÏÞÓÚͬʱ¾¹ý×Ö½ÚÂë±àÒëµÄ´úÂë¡£ ͬÑùµÄÏÞÖÆÒ²ÊÊÓÃÓÚ?getattr() ,?setattr() ?ºÍ?delattr() ,ÒÔ¼°¶ÔÓÚ?__dict__ ?µÄÖ±½ÓÒýÓá£
9.7.?ÔÓÏî˵Ã÷
ÓÐʱ»áÐèҪʹÓÃÀàËÆÓÚ Pascal µÄ¡°record¡±»ò C µÄ¡°struct¡±ÕâÑùµÄÊý¾ÝÀàÐÍ,½«Ò»Ð©ÃüÃûÊý¾ÝÏîÀ¦°óÔÚÒ»Æð¡£ ÕâÖÖÇé¿öÊʺ϶¨ÒåÒ»¸ö¿ÕÀà:
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
Ò»¶ÎÐèÒªÌض¨³éÏóÊý¾ÝÀàÐ굀 Python ´úÂëÍùÍù¿ÉÒÔ±»´«ÈëÒ»¸öÄ£ÄâÁ˸ÃÊý¾ÝÀàÐ͵ķ½·¨µÄÀà×÷ΪÌæ´ú¡£ ÀýÈç,Èç¹ûÄãÓÐÒ»¸ö»ùÓÚÎļþ¶ÔÏóÀ´¸ñʽ»¯Ä³Ð©Êý¾ÝµÄº¯Êý,Äã¿ÉÒÔ¶¨ÒåÒ»¸ö´øÓÐ?read() ?ºÍ?readline() ?·½·¨´Ó×Ö·û´®»º´æ»ñÈ¡Êý¾ÝµÄÀà,²¢½«Æä×÷Ϊ²ÎÊý´«Èë¡£
ʵÀý·½·¨¶ÔÏóÒ²¾ßÓÐÊôÐÔ:?m.__self__ ?¾ÍÊÇ´øÓÐ?m() ?·½·¨µÄʵÀý¶ÔÏó,¶ø?m.__func__ ?ÔòÊǸ÷½·¨Ëù¶ÔÓ¦µÄº¯Êý¶ÔÏó¡£
9.8.?µü´úÆ÷
µ½Ä¿Ç°ÎªÖ¹,Äú¿ÉÄÜÒѾעÒâµ½´ó¶àÊýÈÝÆ÷¶ÔÏ󶼿ÉÒÔʹÓÃ?for?Óï¾ä:
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile.txt"):
print(line, end='')
ÕâÖÖ·ÃÎÊ·ç¸ñÇåÎú¡¢¼ò½àÓÖ·½±ã¡£ µü´úÆ÷µÄʹÓ÷dz£Æձ鲢ʹµÃ Python ³ÉΪһ¸öͳһµÄÕûÌå¡£ ÔÚÄ»ºó,for?Óï¾ä»áÔÚÈÝÆ÷¶ÔÏóÉϵ÷ÓÃ?iter()¡£ ¸Ãº¯Êý·µ»ØÒ»¸ö¶¨ÒåÁË?__next__()?·½·¨µÄµü´úÆ÷¶ÔÏó,´Ë·½·¨½«ÖðÒ»·ÃÎÊÈÝÆ÷ÖеÄÔªËØ¡£ µ±ÔªËØÓþ¡Ê±,__next__()?½«Òý·¢?StopIteration?Òì³£À´Í¨ÖªÖÕÖ¹?for ?Ñ»·¡£ Äã¿ÉÒÔʹÓÃ?next()?ÄÚÖú¯ÊýÀ´µ÷ÓÃ?__next__()?·½·¨;Õâ¸öÀý×ÓÏÔʾÁËËüµÄÔË×÷·½Ê½:
>>>
>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x10c90e650>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
next(it)
StopIteration
¿´¹ýµü´úÆ÷ÐÒéµÄÄ»ºó»úÖÆ,¸øÄãµÄÀàÌí¼Óµü´úÆ÷ÐÐΪ¾ÍºÜÈÝÒ×ÁË¡£ ¶¨ÒåÒ»¸ö?__iter__() ?·½·¨À´·µ»ØÒ»¸ö´øÓÐ?__next__()?·½·¨µÄ¶ÔÏó¡£ Èç¹ûÀàÒѶ¨ÒåÁË?__next__() ,Ôò?__iter__() ?¿ÉÒÔ¼òµ¥µØ·µ»Ø?self :
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>>
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
... print(char)
...
m
a
p
s
9.9.?Éú³ÉÆ÷
Éú³ÉÆ÷?ÊÇÒ»¸öÓÃÓÚ´´½¨µü´úÆ÷µÄ¼òµ¥¶øÇ¿´óµÄ¹¤¾ß¡£ ËüÃǵÄд·¨ÀàËÆÓÚ±ê×¼µÄº¯Êý,µ«µ±ËüÃÇÒª·µ»ØÊý¾Ýʱ»áʹÓÃ?yield?Óï¾ä¡£ ÿ´ÎÔÚÉú³ÉÆ÷Éϵ÷ÓÃ?next()?ʱ,Ëü»á´ÓÉÏ´ÎÀ뿪µÄλÖûָ´Ö´ÐÐ(Ëü»á¼ÇסÉÏ´ÎÖ´ÐÐÓï¾äʱµÄËùÓÐÊý¾ÝÖµ)¡£ Ò»¸öÏÔʾÈçºÎ·Ç³£ÈÝÒ׵ش´½¨Éú³ÉÆ÷µÄʾÀýÈçÏÂ:
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
>>>
>>> for char in reverse('golf'):
... print(char)
...
f
l
o
g
¿ÉÒÔÓÃÉú³ÉÆ÷À´Íê³ÉµÄ²Ù×÷ͬÑù¿ÉÒÔÓÃÇ°Ò»½ÚËùÃèÊöµÄ»ùÓÚÀàµÄµü´úÆ÷À´Íê³É¡£ µ«Éú³ÉÆ÷µÄд·¨¸üΪ½ô´Õ,ÒòΪËü»á×Ô¶¯´´½¨?__iter__() ?ºÍ?__next__()?·½·¨¡£
ÁíÒ»¸ö¹Ø¼üÌØÐÔÔÚÓÚ¾Ö²¿±äÁ¿ºÍÖ´ÐÐ״̬»áÔÚÿ´Îµ÷ÓÃÖ®¼ä×Ô¶¯±£´æ¡£ ÕâʹµÃ¸Ãº¯ÊýÏà±ÈʹÓÃ?self.index ?ºÍ?self.data ?ÕâÖÖʵÀý±äÁ¿µÄ·½Ê½¸üÒ×±àдÇÒ¸üΪÇåÎú¡£
³ýÁË»á×Ô¶¯´´½¨·½·¨ºÍ±£´æ³ÌÐò״̬,µ±Éú³ÉÆ÷ÖÕ½áʱ,ËüÃÇ»¹»á×Ô¶¯Òý·¢?StopIteration¡£ ÕâЩÌØÐÔ½áºÏÔÚÒ»Æð,ʹµÃ´´½¨µü´úÆ÷ÄÜÓë±àд³£¹æº¯ÊýÒ»ÑùÈÝÒס£
9.10.?Éú³ÉÆ÷±í´ïʽ
ijЩ¼òµ¥µÄÉú³ÉÆ÷¿ÉÒÔд³É¼ò½àµÄ±í´ïʽ´úÂë,ËùÓÃÓï·¨ÀàËÆÁбíÍƵ¼Ê½,µ«Íâ²ãΪԲÀ¨ºÅ¶ø·Ç·½À¨ºÅ¡£ ÕâÖÖ±í´ïʽ±»Éè¼ÆÓÃÓÚÉú³ÉÆ÷½«Á¢¼´±»Íâ²ãº¯ÊýËùʹÓõÄÇé¿ö¡£ Éú³ÉÆ÷±í´ïʽÏà±ÈÍêÕûµÄÉú³ÉÆ÷¸ü½ô´Õµ«½Ï²»Áé»î,Ïà±ÈµÈЧµÄÁбíÍƵ¼Ê½Ôò¸üΪ½ÚÊ¡ÄÚ´æ¡£
ʾÀý:
>>>
>>> sum(i*i for i in range(10)) # sum of squares
285
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec)) # dot product
260
>>> unique_words = set(word for line in page for word in line.split())
>>> valedictorian = max((student.gpa, student.name) for student in graduates)
>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']
±¸×¢
1
´æÔÚÒ»¸öÀýÍâ¡£ Ä£¿é¶ÔÏóÓÐÒ»¸öÃØÃܵÄÖ»¶ÁÊôÐÔ?__dict__,Ëü·µ»ØÓÃÓÚʵÏÖÄ£¿éÃüÃû¿Õ¼äµÄ×Öµä;__dict__?ÊÇÊôÐÔµ«²»ÊÇÈ«¾ÖÃû³Æ¡£ ÏÔÈ»,ʹÓÃÕâ¸ö½«Î¥·´ÃüÃû¿Õ¼äʵÏֵijéÏó,Ó¦µ±½ö±»ÓÃÓÚʺóµ÷ÊÔÆ÷Ö®ÀàµÄ³¡ºÏ¡£
10.?±ê×¼¿â¼ò½é
10.1.?²Ù×÷ϵͳ½Ó¿Ú
os?Ä£¿éÌṩÁËÐí¶àÓë²Ù×÷ϵͳ½»»¥µÄº¯Êý:
>>>
>>> import os
>>> os.getcwd() # Return the current working directory
'C:\\Python311'
>>> os.chdir('/server/accesslogs') # Change current working directory
>>> os.system('mkdir today') # Run the command mkdir in the system shell
0
Ò»¶¨ÒªÊ¹ÓÃ?import?os ?¶ø²»ÊÇ?from?os?import?* ?¡£Õ⽫±ÜÃâÄÚ½¨µÄ?open()?º¯Êý±»?os.open()?ÒþʽÌæ»»µô,ÒòΪËüÃǵÄʹÓ÷½Ê½´ó²»Ïàͬ¡£
ÄÚÖõÄ?dir()?ºÍ?help()?º¯Êý¿ÉÓÃ×÷½»»¥Ê½¸¨Öú¹¤¾ß,ÓÃÓÚ´¦Àí´óÐÍÄ£¿é,Èç?os:
>>>
>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>
¶ÔÓÚÈÕ³£ÎļþºÍĿ¼¹ÜÀíÈÎÎñ,?shutil?Ä£¿éÌṩÁ˸üÒ×ÓÚʹÓõĸü¸ß¼¶±ðµÄ½Ó¿Ú:
>>>
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'
10.2.?ÎļþͨÅä·û
glob?Ä£¿éÌṩÁËÒ»¸öÔÚĿ¼ÖÐʹÓÃͨÅä·ûËÑË÷´´½¨ÎļþÁбíµÄº¯Êý:
>>>
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
10.3.?ÃüÁîÐвÎÊý
ͨÓÃʵÓóÌÐò½Å±¾Í¨³£ÐèÒª´¦ÀíÃüÁîÐвÎÊý¡£ÕâЩ²ÎÊý×÷ΪÁбí´æ´¢ÔÚ?sys?Ä£¿éµÄ?argv?ÊôÐÔÖС£ÀýÈç,ÒÔÏÂÊä³öÀ´×ÔÔÚÃüÁîÐÐÔËÐÐ?python?demo.py?one?two?three
>>>
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
argparse?Ä£¿éÌṩÁËÒ»ÖÖ¸ü¸´ÔӵĻúÖÆÀ´´¦ÀíÃüÁîÐвÎÊý¡£ ÒÔϽű¾¿ÉÌáÈ¡Ò»¸ö»ò¶à¸öÎļþÃû,²¢¿ÉÑ¡ÔñÒªÏÔʾµÄÐÐÊý:
import argparse
parser = argparse.ArgumentParser(
prog='top',
description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)
µ±ÔÚͨ¹ý?python?top.py?--lines=5?alpha.txt?beta.txt ?ÔÚÃüÁîÐÐÔËÐÐʱ,¸Ã½Å±¾»á½«?args.lines ?ÉèΪ?5 ?²¢½«?args.filenames ?ÉèΪ?['alpha.txt',?'beta.txt'] ¡£
10.4.?´íÎóÊä³öÖض¨ÏòºÍ³ÌÐòÖÕÖ¹
sys?Ä£¿é»¹¾ßÓÐ?stdin?,?stdout?ºÍ?stderr?µÄÊôÐÔ¡£ºóÕ߶ÔÓÚ·¢³ö¾¯¸æºÍ´íÎóÏûÏ¢·Ç³£ÓÐÓÃ,¼´Ê¹ÔÚ?stdout?±»Öض¨ÏòºóÒ²¿ÉÒÔ¿´µ½ËüÃÇ:
>>>
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
ÖÕÖ¹½Å±¾µÄ×îÖ±½Ó·½·¨ÊÇʹÓÃ?sys.exit() ?¡£
10.5.?×Ö·û´®Ä£Ê½Æ¥Åä
re?Ä£¿éΪ¸ß¼¶×Ö·û´®´¦ÀíÌṩÕýÔò±í´ïʽ¹¤¾ß¡£¶ÔÓÚ¸´ÔÓµÄÆ¥ÅäºÍ²Ù×÷,ÕýÔò±í´ïʽÌṩ¼ò½à,ÓÅ»¯µÄ½â¾ö·½°¸:
>>>
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
µ±Ö»ÐèÒª¼òµ¥µÄ¹¦ÄÜʱ,Ê×Ñ¡×Ö·û´®·½·¨ÒòΪËüÃǸüÈÝÒ×ÔĶÁºÍµ÷ÊÔ:
>>>
>>> 'tea for too'.replace('too', 'two')
'tea for two'
10.6.?Êýѧ
math?Ä£¿éÌṩ¶Ô¸¡µãÊýѧµÄµ×²ãC¿âº¯ÊýµÄ·ÃÎÊ:
>>>
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
random?Ä£¿éÌṩÁ˽øÐÐËæ»úÑ¡ÔñµÄ¹¤¾ß:
>>>
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10) # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random() # random float
0.17970987693706186
>>> random.randrange(6) # random integer chosen from range(6)
4
statistics?Ä£¿é¼ÆËãÊýÖµÊý¾ÝµÄ»ù±¾Í³¼ÆÊôÐÔ(¾ùÖµ,ÖÐλÊý,·½²îµÈ):
>>>
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095
SciPyÏîÄ¿ <https://scipy.org> ÓÐÐí¶àÆäËûÄ£¿éÓÃÓÚÊýÖµ¼ÆËã¡£
10.7.?»¥ÁªÍø·ÃÎÊ
ÓÐÐí¶àÄ£¿é¿ÉÓÃÓÚ·ÃÎÊ»¥ÁªÍøºÍ´¦Àí»¥ÁªÍøÐÒé¡£ÆäÖÐÁ½¸ö×î¼òµ¥µÄ?urllib.request?ÓÃÓÚ´ÓURL¼ìË÷Êý¾Ý,ÒÔ¼°?smtplib?ÓÃÓÚ·¢ËÍÓʼþ:
>>>
>>> from urllib.request import urlopen
>>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
... for line in response:
... line = line.decode() # Convert bytes to a str
... if line.startswith('datetime'):
... print(line.rstrip()) # Remove trailing newline
...
datetime: 2022-01-01T01:36:47.689215+00:00
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()
(Çë×¢Òâ,µÚ¶þ¸öʾÀýÐèÒªÔÚlocalhostÉÏÔËÐеÄÓʼþ·þÎñÆ÷¡£)
10.8.?ÈÕÆÚºÍʱ¼ä
datetime?Ä£¿éÌṩÁËÒÔ¼òµ¥ºÍ¸´Ôӵķ½Ê½²Ù×÷ÈÕÆÚºÍʱ¼äµÄÀà¡£ËäȻ֧³ÖÈÕÆÚºÍʱ¼äËã·¨,µ«ÊµÏÖµÄÖصãÊÇÓÐЧµÄ³ÉÔ±ÌáÈ¡ÒÔ½øÐÐÊä³ö¸ñʽ»¯ºÍ²Ù×÷¡£¸ÃÄ£¿é»¹Ö§³Ö¿É¸Ð֪ʱÇøµÄ¶ÔÏó¡£
>>>
>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
10.9.?Êý¾ÝѹËõ
³£¼ûµÄÊý¾Ý´æµµºÍѹËõ¸ñʽÓÉÄ£¿éÖ±½ÓÖ§³Ö,°üÀ¨:zlib,?gzip,?bz2,?lzma,?zipfile?ºÍ?tarfile¡£:
>>>
>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979
10.10.?ÐÔÄܲâÁ¿
һЩPythonÓû§¶ÔÁ˽âͬһÎÊÌâµÄ²»Í¬·½·¨µÄÏà¶ÔÐÔÄܲúÉúÁËŨºñµÄÐËȤ¡£ PythonÌṩÁËÒ»ÖÖ¿ÉÒÔÁ¢¼´»Ø´ðÕâЩÎÊÌâµÄ²âÁ¿¹¤¾ß¡£
ÀýÈç,Ôª×é·â°üºÍ²ð°ü¹¦ÄÜÏà±È´«Í³µÄ½»»»²ÎÊý¿ÉÄܸü¾ßÎüÒýÁ¦¡£timeit?Ä£¿é¿ÉÒÔ¿ìËÙÑÝʾÔÚÔËÐÐЧÂÊ·½ÃæÒ»¶¨µÄÓÅÊÆ:
>>>
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
Óë?timeit?µÄ¾«Ï¸Á£¶È¼¶±ðÏà·´,?profile?ºÍ?pstats?Ä£¿éÌṩÁËÓÃÓÚÔڽϴóµÄ´úÂë¿éÖÐʶ±ðʱ¼ä¹Ø¼ü²¿·ÖµÄ¹¤¾ß¡£
10.11.?ÖÊÁ¿¿ØÖÆ
¿ª·¢¸ßÖÊÁ¿Èí¼þµÄÒ»ÖÖ·½·¨ÊÇÔÚ¿ª·¢¹ý³ÌÖÐΪÿ¸öº¯Êý±àд²âÊÔ,²¢ÔÚ¿ª·¢¹ý³ÌÖо³£ÔËÐÐÕâЩ²âÊÔ¡£
doctest?Ä£¿éÌṩÁËÒ»¸ö¹¤¾ß,ÓÃÓÚɨÃèÄ£¿é²¢ÑéÖ¤³ÌÐòÎĵµ×Ö·û´®ÖÐǶÈëµÄ²âÊÔ¡£²âÊÔ¹¹Ôì¾ÍÏñ½«µäÐ͵÷Óü°Æä½á¹û¼ôÇв¢Õ³Ìùµ½Îĵµ×Ö·û´®Ò»Ñù¼òµ¥¡£Õâͨ¹ýÏòÓû§ÌṩʾÀýÀ´¸Ä½øÎĵµ,²¢ÇÒËüÔÊÐídoctestÄ£¿éÈ·±£´úÂë±£³Ö¶ÔÎĵµµÄÕæʵ:
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod() # automatically validate the embedded tests
unittest?Ä£¿é²»Ïñ?doctest?Ä£¿éÄÇÑùÒ×ÓÚʹÓÃ,µ«ËüÔÊÐíÔÚÒ»¸öµ¥¶ÀµÄÎļþÖÐά»¤¸üÈ«ÃæµÄ²âÊÔ¼¯:
import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
with self.assertRaises(ZeroDivisionError):
average([])
with self.assertRaises(TypeError):
average(20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
10.12.?×Ô´øµç³Ø
PythonÓС°×Ô´øµç³Ø¡±µÄÀíÄͨ¹ýÆä°üµÄ¸´ÔÓºÍÇ¿´ó¹¦ÄÜ¿ÉÒÔ×îºÃµØ¿´µ½ÕâÒ»µã¡£ÀýÈç:
-
xmlrpc.client?ºÍ?xmlrpc.server?Ä£¿éʹµÃʵÏÖÔ¶³Ì¹ý³Ìµ÷Óñä³ÉÁËС²ËÒ»µú¡£ ¾¡¹Ü´æÔÚÓÚÄ£¿éÃû³ÆÖÐ,µ«Óû§²»ÐèÒªÖ±½ÓÁ˽â»ò´¦Àí XML¡£ -
?email?°üÊÇÒ»¸öÓÃÓÚ¹ÜÀíµç×ÓÓʼþµÄ¿â,°üÀ¨MIMEºÍÆäËû·ûºÏ?RFC 2822?¹æ·¶µÄÓʼþÎĵµ¡£Óë?smtplib?ºÍ?poplib?²»Í¬(ËüÃÇʵ¼ÊÉÏ×öµÄÊÇ·¢ËͺͽÓÊÕÏûÏ¢),µç×ÓÓʼþ°üÌṩÍêÕûµÄ¹¤¾ß¼¯,ÓÃÓÚ¹¹½¨»ò½âÂ븴ÔÓµÄÏûÏ¢½á¹¹(°üÀ¨¸½¼þ)ÒÔ¼°ÊµÏÖ»¥ÁªÍø±àÂëºÍ±êÍ·ÐÒé¡£ -
?json?°üΪ½âÎöÕâÖÖÁ÷ÐеÄÊý¾Ý½»»»¸ñʽÌṩÁËÇ¿´óµÄÖ§³Ö¡£?csv?Ä£¿éÖ§³ÖÒÔ¶ººÅ·Ö¸ôÖµ¸ñʽֱ½Ó¶ÁÈ¡ºÍдÈëÎļþ,ÕâÖÖ¸ñʽͨ³£ÎªÊý¾Ý¿âºÍµç×Ó±í¸ñËùÖ§³Ö¡£ XML ´¦ÀíÓÉ?xml.etree.ElementTree?,?xml.dom?ºÍ?xml.sax?°üÖ§³Ö¡£ÕâЩģ¿éºÍÈí¼þ°ü¹²Í¬´ó´ó¼ò»¯ÁË Python Ó¦ÓóÌÐòºÍÆäËû¹¤¾ßÖ®¼äµÄÊý¾Ý½»»»¡£ -
?sqlite3?Ä£¿éÊÇ SQLite Êý¾Ý¿â¿âµÄ°ü×°Æ÷,ÌṩÁËÒ»¸ö¿ÉÒÔʹÓÃÉÔ΢·Ç±ê×¼µÄ SQL Óï·¨¸üкͷÃÎʵij־ÃÊý¾Ý¿â¡£ -
¹ú¼Ê»¯ÓÉÐí¶àÄ£¿éÖ§³Ö,°üÀ¨?gettext?,?locale?,ÒÔ¼°?codecs?°ü¡£
?
11.?±ê×¼¿â¼ò½é ¡ª¡ª µÚ¶þ²¿·Ö
µÚ¶þ²¿·Öº¸ÇÁËרҵ±à³ÌËùÐèÒªµÄ¸ü¸ß¼¶µÄÄ£¿é¡£ÕâЩģ¿éºÜÉÙÓÃÔÚС½Å±¾ÖС£
11.1.?¸ñʽ»¯Êä³ö
reprlib?Ä£¿éÌṩÁËÒ»¸ö¶¨ÖÆ»¯°æ±¾µÄ?repr()?º¯Êý,ÓÃÓÚËõÂÔÏÔʾ´óÐÍ»òÉî²ãǶÌ×µÄÈÝÆ÷¶ÔÏó:
>>>
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
pprint?Ä£¿éÌṩÁ˸ü¼Ó¸´ÔӵĴòÓ¡¿ØÖÆ,ÆäÊä³öµÄÄÚÖöÔÏóºÍÓû§×Ô¶¨Òå¶ÔÏóÄܹ»±»½âÊÍÆ÷Ö±½Ó¶ÁÈ¡¡£µ±Êä³ö½á¹û¹ý³¤¶øÐèÒªÕÛÐÐʱ,¡°ÃÀ»¯Êä³ö»úÖÆ¡±»áÌí¼Ó»»ÐзûºÍËõ½ø,ÒÔ¸üÇå³þµØչʾÊý¾Ý½á¹¹:
>>>
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]
textwrap?Ä£¿éÄܹ»¸ñʽ»¯Îı¾¶ÎÂä,ÒÔÊÊÓ¦¸ø¶¨µÄÆÁÄ»¿í¶È:
>>>
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
locale?Ä£¿é´¦ÀíÓëÌض¨µØÓòÎÄ»¯Ïà¹ØµÄÊý¾Ý¸ñʽ¡£locale Ä£¿éµÄ format º¯Êý°üº¬Ò»¸ö grouping ÊôÐÔ,¿ÉÖ±½Ó½«Êý×Ö¸ñʽ»¯Îª´øÓÐ×é·Ö¸ô·ûµÄÑùʽ:
>>>
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv() # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
11.2.?Ä£°å
string?Ä£¿é°üº¬Ò»¸öͨÓõÄ?Template?Àà,¾ßÓÐÊÊÓÃÓÚ×îÖÕÓû§µÄ¼ò»¯Óï·¨¡£ËüÔÊÐíÓû§ÔÚ²»¸ü¸ÄÓ¦ÓÃÂß¼µÄÇé¿ö϶¨ÖÆ×Ô¼ºµÄÓ¦Óá£
ÉÏÊö¸ñʽ»¯²Ù×÷ÊÇͨ¹ýռλ·ûʵÏÖµÄ,ռλ·ûÓÉ?$ ?¼ÓÉϺϷ¨µÄ Python ±êʶ·û(Ö»ÄÜ°üº¬×Öĸ¡¢Êý×ÖºÍÏ»®Ïß)¹¹³É¡£Ò»µ©Ê¹Óû¨À¨ºÅ½«Õ¼Î»·ûÀ¨ÆðÀ´,¾Í¿ÉÒÔÔÚºóÃæÖ±½Ó¸úÉϸü¶àµÄ×ÖĸºÍÊý×Ö¶øÎÞÐè¿Õ¸ñ·Ö¸î¡£$$ ?½«±»×ªÒå³Éµ¥¸ö×Ö·û?$ :
>>>
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
Èç¹ûÔÚ×Öµä»ò¹Ø¼ü×Ö²ÎÊýÖÐδÌṩij¸öռλ·ûµÄÖµ,ÄÇô?substitute()?·½·¨½«Å׳ö?KeyError¡£¶ÔÓÚÓʼþºÏ²¢ÀàÐ͵ÄÓ¦ÓÃ,Óû§ÌṩµÄÊý¾ÝÓпÉÄÜÊDz»ÍêÕûµÄ,´ËʱʹÓÃ?safe_substitute()?·½·¨¸ü¼ÓºÏÊÊ ¡ª¡ª Èç¹ûÊý¾Ýȱʧ,Ëü»áÖ±½Ó½«Õ¼Î»·ûÔÑù±£Áô¡£
>>>
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
Template µÄ×ÓÀà¿ÉÒÔ×Ô¶¨Òå·Ö¸ô·û¡£ÀýÈç,ÒÔÏÂÊÇij¸öÕÕƬä¯ÀÀÆ÷µÄÅúÁ¿ÖØÃüÃû¹¦ÄÜ,²ÉÓÃÁË°Ù·ÖºÅ×÷ΪÈÕÆÚ¡¢ÕÕƬÐòºÅºÍÕÕƬ¸ñʽµÄռλ·û:
>>>
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename)
... newname = t.substitute(d=date, n=i, f=ext)
... print('{0} --> {1}'.format(filename, newname))
img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
Ä£°åµÄÁíÒ»¸öÓ¦ÓÃÊǽ«³ÌÐòÂß¼Óë¶àÑùµÄ¸ñʽ»¯Êä³öϸ½Ú·ÖÀ뿪À´¡£ÕâʹµÃ¶Ô XML Îļþ¡¢´¿Îı¾±¨±íºÍ HTML ÍøÂ籨±íʹÓÃ×Ô¶¨ÒåÄ£°å³ÉΪ¿ÉÄÜ¡£
11.3.?ʹÓöþ½øÖÆÊý¾Ý¼Ç¼¸ñʽ
struct?Ä£¿éÌṩÁË?pack()?ºÍ?unpack()?º¯Êý,ÓÃÓÚ´¦Àí²»¶¨³¤¶ÈµÄ¶þ½øÖƼǼ¸ñʽ¡£ÏÂÃæµÄÀý×ÓչʾÁËÔÚ²»Ê¹ÓÃ?zipfile?Ä£¿éµÄÇé¿öÏÂ,ÈçºÎÑ»·±éÀúÒ»¸ö ZIP ÎļþµÄËùÓÐÍ·ÐÅÏ¢¡£Pack ´úÂë?"H" ?ºÍ?"I" ?·Ö±ð´ú±íÁ½×Ö½ÚºÍËÄ×Ö½ÚÎÞ·ûºÅÕûÊý¡£"<" ?´ú±íËüÃÇÊDZê×¼³ß´çµÄС¶Ë×Ö½ÚÐò:
import struct
with open('myfile.zip', 'rb') as f:
data = f.read()
start = 0
for i in range(3): # show the first 3 file headers
start += 14
fields = struct.unpack('<IIIHH', data[start:start+16])
crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print(filename, hex(crc32), comp_size, uncomp_size)
start += extra_size + comp_size # skip to the next header
11.4.?¶àÏß³Ì
Ïß³ÌÊÇÒ»ÖÖ¶ÔÓÚ·Ç˳ÐòÒÀÀµµÄ¶à¸öÈÎÎñ½øÐнâñîµÄ¼¼Êõ¡£¶àÏ߳̿ÉÒÔÌá¸ßÓ¦ÓõÄÏìӦЧÂÊ,µ±½ÓÊÕÓû§ÊäÈëµÄͬʱ,±£³ÖÆäËûÈÎÎñÔÚºǫ́ÔËÐС£Ò»¸öÓйصÄÓ¦Óó¡¾°ÊÇ,½« I/O ºÍ¼ÆËãÔËÐÐÔÚÁ½¸ö²¢ÐеÄÏß³ÌÖС£
ÒÔÏ´úÂëչʾÁ˸߽׵Ä?threading?Ä£¿éÈçºÎÔÚºǫ́ÔËÐÐÈÎÎñ,ÇÒ²»Ó°ÏìÖ÷³ÌÐòµÄ¼ÌÐøÔËÐÐ:
import threading, zipfile
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile)
f.close()
print('Finished background zip of:', self.infile)
background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')
background.join() # Wait for the background task to finish
print('Main program waited until background was done.')
¶àÏß³ÌÓ¦ÓÃÃæÁÙµÄÖ÷ÒªÌôÕ½ÊÇ,Ï໥е÷µÄ¶à¸öÏß³ÌÖ®¼äÐèÒª¹²ÏíÊý¾Ý»òÆäËû×ÊÔ´¡£Îª´Ë,threading Ä£¿éÌṩÁ˶à¸öͬ²½²Ù×÷ÔÓï,°üÀ¨Ïß³ÌËø¡¢Ê¼þ¡¢Ìõ¼þ±äÁ¿ºÍÐźÅÁ¿¡£
¾¡¹ÜÕâЩ¹¤¾ß·Ç³£Ç¿´ó,µ«Î¢Ð¡µÄÉè¼Æ´íÎóÈ´¿ÉÒÔµ¼ÖÂһЩÄÑÒÔ¸´ÏÖµÄÎÊÌâ¡£Òò´Ë,ʵÏÖ¶àÈÎÎñÐ×÷µÄÊ×Ñ¡·½·¨Êǽ«ËùÓжÔ×ÊÔ´µÄÇëÇó¼¯Öе½Ò»¸öÏß³ÌÖÐ,È»ºóʹÓÃ?queue?Ä£¿éÏò¸ÃÏ̹߳©Ó¦À´×ÔÆäËûÏ̵߳ÄÇëÇó¡£ Ó¦ÓóÌÐòʹÓÃ?Queue?¶ÔÏó½øÐÐÏ̼߳äͨÐźÍе÷,¸üÒ×ÓÚÉè¼Æ,¸üÒ׶Á,¸ü¿É¿¿¡£
11.5.?ÈÕÖ¾¼Ç¼
logging?Ä£¿éÌṩ¹¦ÄÜÆëÈ«ÇÒÁé»îµÄÈÕÖ¾¼Ç¼ϵͳ¡£ÔÚ×î¼òµ¥µÄÇé¿öÏÂ,ÈÕÖ¾ÏûÏ¢±»·¢Ë͵½Îļþ»ò?sys.stderr
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
Õâ»á²úÉúÒÔÏÂÊä³ö:
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
ĬÈÏÇé¿öÏÂ,informational ºÍ debugging ÏûÏ¢±»Ñ¹ÖÆ,Êä³ö»á·¢Ë͵½±ê×¼´íÎóÁ÷¡£ÆäËûÊä³öÑ¡Ïî°üÀ¨½«ÏûϢת·¢µ½µç×ÓÓʼþ,Êý¾Ý±¨,Ì×½Ó×Ö»ò HTTP ·þÎñÆ÷¡£ÐµĹýÂËÆ÷¿ÉÒÔ¸ù¾ÝÏûÏ¢ÓÅÏȼ¶Ñ¡Ôñ²»Í¬µÄ·ÓÉ·½Ê½:DEBUG ,INFO ,WARNING ,ERROR ,ºÍ?CRITICAL ¡£
ÈÕ־ϵͳ¿ÉÒÔÖ±½Ó´Ó Python ÅäÖÃ,Ò²¿ÉÒÔ´ÓÓû§ÅäÖÃÎļþ¼ÓÔØ,ÒÔ±ã×Ô¶¨ÒåÈÕÖ¾¼Ç¼¶øÎÞÐè¸ü¸ÄÓ¦ÓóÌÐò¡£
11.6.?ÈõÒýÓÃ
Python »á×Ô¶¯½øÐÐÄÚ´æ¹ÜÀí(¶Ô´ó¶àÊý¶ÔÏó½øÐÐÒýÓüÆÊý²¢Ê¹ÓÃ?garbage collection?À´Çå³ýÑ»·ÒýÓÃ)¡£ µ±Ä³¸ö¶ÔÏóµÄ×îºóÒ»¸öÒýÓñ»ÒƳýºó²»¾Ã¾Í»áÊÍ·ÅÆäËùÕ¼ÓõÄÄÚ´æ¡£
´Ë·½Ê½¶Ô´ó¶àÊýÓ¦ÓÃÀ´Ëµ¶¼ÊÊÓÃ,µ«Å¼¶ûÒ²±ØÐëÔÚ¶ÔÏó³ÖÐø±»ÆäËû¶ÔÏóËùʹÓÃʱ¸ú×ÙËüÃÇ¡£ ²»ÐÒµÄÊÇ,¸ú×ÙËüÃǽ«´´½¨Ò»¸ö»áÁîÆäÓÀ¾Ã»¯µÄÒýÓá£?weakref?Ä£¿éÌṩµÄ¹¤¾ß¿ÉÒÔ²»±Ø´´½¨ÒýÓþÍÄܸú×Ù¶ÔÏó¡£ µ±¶ÔÏó²»ÔÙÐèҪʱ,Ëü½«×Ô¶¯´ÓÒ»¸öÈõÒýÓñíÖб»ÒƳý,²¢ÎªÈõÒýÓöÔÏó´¥·¢Ò»¸ö»Øµ÷¡£ µäÐÍÓ¦ÓðüÀ¨¶Ô´´½¨¿ªÏú½Ï´óµÄ¶ÔÏó½øÐлº´æ:
>>>
>>> import weakref, gc
>>> class A:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return str(self.value)
...
>>> a = A(10) # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
10
>>> del a # remove the one reference
>>> gc.collect() # run garbage collection right away
0
>>> d['primary'] # entry was automatically removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
d['primary'] # entry was automatically removed
File "C:/python311/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
11.7.?ÓÃÓÚ²Ù×÷ÁбíµÄ¹¤¾ß
Ðí¶à¶ÔÓÚÊý¾Ý½á¹¹µÄÐèÇó¿ÉÒÔͨ¹ýÄÚÖÃÁбíÀàÐÍÀ´Âú×ã¡£ µ«ÊÇ,ÓÐʱҲ»áÐèÒª¾ßÓв»Í¬Ð§·Ñ±ÈµÄÌæ´úʵÏÖ¡£
array?Ä£¿éÌṩÁËÒ»ÖÖ?array()?¶ÔÏó,ËüÀàËÆÓÚÁбí,µ«Ö»ÄÜ´æ´¢ÀàÐÍÒ»ÖµÄÊý¾ÝÇÒ´æ´¢Ãܼ¯¸ü¸ß¡£ ÏÂÃæµÄÀý×ÓÑÝʾÁËÒ»¸öÒÔÁ½¸ö×Ö½ÚΪ´æ´¢µ¥ÔªµÄÎÞ·ûºÅ¶þ½øÖÆÊýÖµµÄÊý×é (ÀàÐÍÂëΪ?"H" ),¶ø¶ÔÓÚÆÕͨÁбíÀ´Ëµ,ÿ¸öÌõÄ¿´æ´¢Îª±ê×¼ Python µÄ int ¶ÔÏóͨ³£ÒªÕ¼ÓÃ16 ¸ö×Ö½Ú:
>>>
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
collections?Ä£¿éÌṩÁËÒ»ÖÖ?deque()?¶ÔÏó,ËüÀàËÆÓÚÁбí,µ«´Ó×ó¶ËÌí¼ÓºÍµ¯³öµÄËٶȽϿì,¶øÔÚÖмä²éÕÒµÄËٶȽÏÂý¡£ ´ËÖÖ¶ÔÏóÊÊÓÃÓÚʵÏÖ¶ÓÁк͹ã¶ÈÓÅÏÈÊ÷ËÑË÷:
>>>
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
node = unsearched.popleft()
for m in gen_moves(node):
if is_goal(m):
return m
unsearched.append(m)
ÔÚÌæ´úµÄÁбíʵÏÖÒÔÍâ,±ê×¼¿âÒ²ÌṩÁËÆäËû¹¤¾ß,ÀýÈç?bisect?Ä£¿é¾ßÓÐÓÃÓÚ²Ù×÷ÓÐÐòÁбíµÄº¯Êý:
>>>
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
heapq?Ä£¿éÌṩÁË»ùÓÚ³£¹æÁбíÀ´ÊµÏֶѵĺ¯Êý¡£ ×îСֵµÄÌõÄ¿×ÜÊDZ£³ÖÔÚλÖÃÁã¡£ Õâ¶ÔÓÚÐèÒªÖظ´·ÃÎÊ×îСԪËضø²»Ï£ÍûÔËÐÐÍêÕûÁбíÅÅÐòµÄÓ¦ÓÃÀ´Ëµ·Ç³£ÓÐÓÃ:
>>>
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) # rearrange the list into heap order
>>> heappush(data, -5) # add a new entry
>>> [heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]
11.8.?Ê®½øÖƸ¡µãÔËËã
decimal?Ä£¿éÌṩÁËÒ»ÖÖ?Decimal?Êý¾ÝÀàÐÍÓÃÓÚÊ®½øÖƸ¡µãÔËËã¡£ Ïà±ÈÄÚÖõÄ?float?¶þ½øÖƸ¡µãʵÏÖ,¸ÃÀàÌرðÊÊÓÃÓÚ
-
²ÆÎñÓ¦ÓúÍÆäËûÐèÒª¾«È·Ê®½øÖƱíʾµÄÓÃ;, -
¿ØÖƾ«¶È, -
¿ØÖÆËÄÉáÎåÈëÒÔÂú×ã·¨ÂÉ»ò¼à¹ÜÒªÇó, -
¸ú×ÙÓÐЧСÊýλ,»ò -
Óû§ÆÚÍû½á¹ûÓëÊÖ¹¤Íê³ÉµÄ¼ÆËãÏàÆ¥ÅäµÄÓ¦ÓóÌÐò¡£
ÀýÈç,ʹÓÃÊ®½øÖƸ¡µãºÍ¶þ½øÖƸ¡µãÊý¼ÆËã70ÃÀ·ÖÊÖ»úºÍ5%Ë°µÄ×Ü·ÑÓÃ,»á²úÉúµÄ²»Í¬½á¹û¡£Èç¹û½á¹ûËÄÉáÎåÈëµ½×î½Ó½üµÄ·ÖÊý²îÒì»á¸ü´ó:
>>>
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73
Decimal?±íʾµÄ½á¹û»á±£Áôβ²¿µÄÁã,²¢¸ù¾Ý¾ßÓÐÁ½¸öÓÐЧλµÄ±»³ËÊý×Ô¶¯ÍƳöËĸöÓÐЧλ¡£ Decimal ¿ÉÒÔÄ£ÄâÊÖ¹¤ÔËËãÀ´±ÜÃâµ±¶þ½øÖƸ¡µãÊýÎÞ·¨¾«È·±íʾʮ½øÖÆÊýʱ»áµ¼ÖµÄÎÊÌâ¡£
¾«È·±íʾÌØÐÔʹµÃ?Decimal?ÀàÄܹ»Ö´ÐжÔÓÚ¶þ½øÖƸ¡µãÊýÀ´Ëµ²»ÊÊÓõÄÄ£ÔËËãºÍÏàµÈÐÔ¼ì²â:
>>>
>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995
>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False
decimal?Ä£¿éÌṩÁËÔËËãËùÐèÒªµÄ×ã¹»¾«¶È:
>>>
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')
6.?±í´ïʽ
±¾Õ½«½âÊÍ Python ÖÐ×é³É±í´ïʽµÄ¸÷ÖÖÔªËصĵĺ¬Òå¡£
Ó﷨עÊÍ:?ÔÚ±¾ÕºͺóÐøÕ½ÚÖÐ,»áʹÓÃÀ©Õ¹ BNF ±ê×¢À´ÃèÊöÓï·¨¶ø²»ÊÇ´Ê·¨·ÖÎö¡£ µ±(ijÖÖÌæ´úµÄ)Óï·¨¹æÔò¾ßÓÐÈçÏÂÐÎʽ
name ::= othername
²¢ÇÒûÓиø³öÓïÒå,ÔòÕâÖÖÐÎʽµÄ?name ?ÔÚÓï·¨ÉÏÓë?othername ?Ïàͬ¡£
6.1.?ËãÊõת»»
µ±¶ÔÏÂÊöij¸öËãÊõÔËËã·ûµÄÃèÊöÖÐʹÓÃÁË¡°ÊýÖµ²ÎÊý±»×ª»»ÎªÆÕͨÀàÐÍ¡±ÕâÑùµÄ˵·¨,ÕâÒâζ×ÅÄÚÖÃÀàÐ͵ÄÔËËã·ûʵÏÖ²ÉÓÃÁËÈçÏÂÔË×÷·½Ê½:
-
Èç¹ûÈÎÒ»²ÎÊýΪ¸´Êý,ÁíÒ»²ÎÊý»á±»×ª»»Îª¸´Êý; -
·ñÔò,Èç¹ûÈÎÒ»²ÎÊýΪ¸¡µãÊý,ÁíÒ»²ÎÊý»á±»×ª»»Îª¸¡µãÊý; -
·ñÔò,Á½ÕßÓ¦¸Ã¶¼ÎªÕûÊý,²»ÐèÒª½øÐÐת»»¡£
ijЩ¸½¼Ó¹æÔò»á×÷ÓÃÓÚÌض¨ÔËËã·û(ÀýÈç,×Ö·û´®×÷Ϊ '%' ÔËËã·ûµÄ×óÔËËã²ÎÊý)¡£ À©Õ¹±ØÐ붨ÒåËüÃÇ×Ô¼ºµÄת»»ÐÐΪ¡£
6.2.?Ô×Ó
¡°Ô×Ó¡±Ö¸±í´ïʽµÄ×î»ù±¾¹¹³ÉÔªËØ¡£ ×î¼òµ¥µÄÔ×ÓÊDZêʶ·ûºÍ×ÖÃæÖµ¡£ ÒÔÔ²À¨ºÅ¡¢·½À¨ºÅ»ò»¨À¨ºÅ°üÀ¨µÄÐÎʽÔÚÓï·¨ÉÏÒ²±»¹éÀàΪÔ×Ó¡£ Ô×ӵľ䷨Ϊ:
atom ::= identifier | literal | enclosure
enclosure ::= parenth_form | list_display | dict_display | set_display
| generator_expression | yield_atom
6.2.1.?±êʶ·û(Ãû³Æ)
×÷ΪÔ×Ó³öÏֵıêʶ·û½Ð×öÃû³Æ¡£ Çë²Î¿´?±êʶ·ûºÍ¹Ø¼ü×Ö?Ò»½ÚÁ˽âÆä´Ê·¨¶¨Òå,ÒÔ¼°?ÃüÃûÓë°ó¶¨?»ñÈ¡ÓйØÃüÃûÓë°ó¶¨µÄÎĵµ¡£
µ±Ãû³Æ±»°ó¶¨µ½Ò»¸ö¶ÔÏóʱ,¶Ô¸ÃÔ×ÓÇóÖµ½«·µ»ØÏàÓ¦¶ÔÏó¡£ µ±Ãû³Æδ±»°ó¶¨Ê±,³¢ÊÔ¶ÔÆäÇóÖµ½«Òý·¢?NameError?Òì³£¡£
˽ÓÐÃû³Æת»»:?µ±ÒÔÎı¾ÐÎʽ³öÏÖÔÚÀඨÒåÖеÄÒ»¸ö±êʶ·ûÒÔÁ½¸ö»ò¸ü¶àÏ»®Ïß¿ªÍ·²¢ÇÒ²»ÒÔÁ½¸ö»ò¸ü¶àÏ»®Ïß½áβ,Ëü»á±»ÊÓΪ¸ÃÀàµÄ?˽ÓÐÃû³Æ¡£ ˽ÓÐÃû³Æ»áÔÚΪÆäÉú³É´úÂë֮ǰ±»×ª»»ÎªÒ»ÖÖ¸ü³¤µÄÐÎʽ¡£ ת»»Ê±»á²åÈëÀàÃû,ÒƳý´òÍ·µÄÏ»®ÏßÔÙÔÚÃû³ÆÇ°Ôö¼ÓÒ»¸öÏ»®Ïß¡£ ÀýÈç,³öÏÖÔÚÒ»¸öÃûΪ?Ham ?µÄÀàÖеıêʶ·û?__spam ?»á±»×ª»»Îª?_Ham__spam ¡£ ÕâÖÖת»»¶ÀÁ¢ÓÚ±êʶ·ûËùʹÓõÄÏà¹Ø¾ä·¨¡£ Èç¹ûת»»ºóµÄÃû³ÆÌ«³¤(³¬¹ý 255 ¸ö×Ö·û),¿ÉÄÜ·¢ÉúÓɾßÌåʵÏÖ¶¨ÒåµÄ½Ø¶Ï¡£ Èç¹ûÀàÃû½öÓÉÏ»®Ïß×é³É,Ôò²»»á½øÐÐת»»¡£
6.2.2.?×ÖÃæÖµ
Python Ö§³Ö×Ö·û´®ºÍ×Ö½Ú´®×ÖÃæÖµ,ÒÔ¼°¼¸ÖÖÊý×Ö×ÖÃæÖµ:
literal ::= stringliteral | bytesliteral
| integer | floatnumber | imagnumber
¶Ô×ÖÃæÖµÇóÖµ½«·µ»ØÒ»¸ö¸ÃÖµËù¶ÔÓ¦ÀàÐ͵ĶÔÏó(×Ö·û´®¡¢×Ö½Ú´®¡¢ÕûÊý¡¢¸¡µãÊý¡¢¸´Êý)¡£ ¶ÔÓÚ¸¡µãÊýºÍÐéÊý(¸´Êý)µÄÇé¿ö,¸ÃÖµ¿ÉÄÜΪ½üËÆÖµ¡£ ÏêÇé²Î¼û?×ÖÃæÖµ¡£
ËùÓÐ×ÖÃæÖµ¶¼¶ÔÓ¦Óë²»¿É±äÊý¾ÝÀàÐÍ,Òò´Ë¶ÔÏó±êʶµÄÖØÒªÐÔ²»ÈçÆäʵ¼ÊÖµ¡£ ¶à´Î¶Ô¾ßÓÐÏàֵͬµÄ×ÖÃæÖµÇóÖµ(²»ÂÛÊÇ·¢ÉúÔÚ³ÌÐòÎı¾µÄÏàͬλÖû¹ÊDz»Í¬Î»ÖÃ)¿ÉÄܵõ½Ïàͬ¶ÔÏó»òÊǾßÓÐÏàֵͬµÄ²»Í¬¶ÔÏó¡£
6.2.3.?´øÔ²À¨ºÅµÄÐÎʽ
´øÔ²À¨ºÅµÄÐÎʽÊÇ°üº¬ÔÚÔ²À¨ºÅÖеĿÉÑ¡±í´ïʽÁÐ±í¡£
parenth_form ::= "(" [starred_expression] ")"
´øÔ²À¨ºÅµÄ±í´ïʽÁÐ±í½«·µ»Ø¸Ã±í´ïʽÁбíËù²úÉúµÄÈκζ«Î÷:Èç¹û¸ÃÁбí°üº¬ÖÁÉÙÒ»¸ö¶ººÅ,Ëü»á²úÉúÒ»¸öÔª×é;·ñÔò,Ëü»á²úÉú¸Ã±í´ïʽÁбíËù¶ÔÓ¦µÄµ¥Ò»±í´ïʽ¡£
Ò»¶ÔÄÚÈÝΪ¿ÕµÄÔ²À¨ºÅ½«²úÉúÒ»¸ö¿ÕµÄÔª×é¶ÔÏó¡£ ÓÉÓÚÔª×éÊDz»¿É±ä¶ÔÏó,Òò´ËÊÊÓÃÓë×ÖÃæÖµÏàͬµÄ¹æÔò(¼´Á½´Î³öÏֵĿÕÔª×é²úÉúµÄ¶ÔÏó¿ÉÄÜÏàͬҲ¿ÉÄܲ»Í¬)¡£
Çë×¢ÒâÔª×é²¢²»ÊÇÓÉÔ²À¨ºÅ¹¹½¨,ʵ¼ÊÆð×÷ÓõÄÊǶººÅ²Ù×÷·û¡£ ÀýÍâÇé¿öÊÇ¿ÕÔª×é,ÕâʱԲÀ¨ºÅ?²ÅÊÇ?±ØÐëµÄ --- ÔÊÐíÔÚ±í´ïʽÖÐʹÓò»´øÔ²À¨ºÅµÄ "¿Õ" »áµ¼ÖÂÆçÒå,²¢»áÔì³É³£¼ûÊäÈë´íÎóÎÞ·¨±»²¶»ñ¡£
6.2.4.?ÁÐ±í¡¢¼¯ºÏÓë×ÖµäµÄÏÔʾ
ΪÁ˹¹½¨ÁÐ±í¡¢¼¯ºÏ»ò×Öµä,Python ÌṩÁËÃûΪ¡°ÏÔʾ¡±µÄÌØÊâ¾ä·¨,ÿ¸öÀàÐ͸÷ÓÐÁ½ÖÖÐÎʽ:
ÍƵ¼Ê½µÄ³£Óþ䷨ԪËØΪ:
comprehension ::= assignment_expression comp_for
comp_for ::= ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter ::= comp_for | comp_if
comp_if ::= "if" or_test [comp_iter]
ÍƵ¼Ê½µÄ½á¹¹ÊÇÒ»¸öµ¥¶À±í´ïʽºóÃæ¼ÓÖÁÉÙÒ»¸ö?for ?×Ó¾äÒÔ¼°Áã¸ö»ò¸ü¶à¸ö?for ?»ò?if ?×Ӿ䡣 ÔÚÕâÖÖÇé¿öÏÂ,ÐÂÈÝÆ÷µÄÔªËزúÉú·½Ê½Êǽ«Ã¿¸ö?for ?»ò?if ?×Ó¾äÊÓΪһ¸ö´úÂë¿é,°´´Ó×óÖÁÓÒµÄ˳ÐòǶÌ×,È»ºóÿ´Îµ½´ï×îÄÚ²ã´úÂë¿éʱ¾Í¶Ô±í´ïʽ½øÐÐÇóÖµÒÔ²úÉúÒ»¸öÔªËØ¡£
²»¹ý,³ýÁË×î×ó±ß?for ?×Ó¾äÖеĿɵü´ú±í´ïʽ,ÍƵ¼Ê½ÊÇÔÚÁíÒ»¸öÒþʽǶÌ×µÄ×÷ÓÃÓòÄÚÖ´Ðеġ£ ÕâÄÜÈ·±£¸³¸øÄ¿±êÁбíµÄÃû³Æ²»»á¡°Ð¹Â¶¡±µ½Íâ²ãµÄ×÷ÓÃÓò¡£
×î×ó±ßµÄ?for ?×Ó¾äÖеĿɵü´ú¶ÔÏó±í´ïʽ»áÖ±½ÓÔÚÍâ²ã×÷ÓÃÓòÖб»ÇóÖµ,È»ºó×÷Ϊһ¸ö²ÎÊý±»´«¸øÒþʽǶÌ×µÄ×÷ÓÃÓò¡£ ºóÐøµÄ?for ?×Ó¾äÒÔ¼°×î×ó²à?for ?×Ó¾äÖеÄÈκÎɸѡÌõ¼þ²»ÄÜÔÚÍâ²ã×÷ÓÃÓòÖб»ÇóÖµ,ÒòΪËüÃÇ¿ÉÄÜÒÀÀµÓÚ´Ó×î×ó²à¿Éµü´ú¶ÔÏóÖлñµÃµÄÖµ¡£ ÀýÈç:?[x*y?for?x?in?range(10)?for?y?in?range(x,?x+10)] ¡£
ΪÁËÈ·±£ÍƵ¼Ê½µÃ³öµÄ½á¹û×ÜÊÇÒ»¸öÀàÐÍÕýÈ·µÄÈÝÆ÷,ÔÚÒþʽǶÌ××÷ÓÃÓòÄÚ½ûֹʹÓÃ?yield ?ºÍ?yield?from ?±í´ïʽ¡£
Since Python 3.6, in an?async?def?function, an?async?for ?clause may be used to iterate over a?asynchronous iterator. A comprehension in an?async?def ?function may consist of either a?for ?or?async?for ?clause following the leading expression, may contain additional?for ?or?async?for ?clauses, and may also use?await?expressions. If a comprehension contains either?async?for ?clauses or?await ?expressions or other asynchronous comprehensions it is called an?asynchronous comprehension. An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. See also?PEP 530.
3.6 а湦ÄÜ:?ÒýÈëÁËÒì²½ÍƵ¼Ê½¡£
ÔÚ 3.8 °æ¸ü¸Ä:?yield ?ºÍ?yield?from ?ÔÚÒþʽǶÌ×µÄ×÷ÓÃÓòÖÐÒѱ»½ûÓá£
ÔÚ 3.11 °æ¸ü¸Ä:?Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous.
6.2.5.?ÁбíÏÔʾ
ÁбíÏÔʾÊÇÒ»¸öÓ÷½À¨ºÅÀ¨ÆðÀ´µÄ¿ÉÄÜΪ¿ÕµÄ±í´ïʽϵÁÐ:
list_display ::= "[" [starred_list | comprehension] "]"
ÁбíÏÔʾ»á²úÉúÒ»¸öеÄÁбí¶ÔÏó,ÆäÄÚÈÝͨ¹ýһϵÁбí´ïʽ»òÒ»¸öÍƵ¼Ê½À´Ö¸¶¨¡£ µ±ÌṩÓɶººÅ·Ö¸ôµÄһϵÁбí´ïʽʱ,ÆäÔªËØ»á´Ó×óÖÁÓÒ±»ÇóÖµ²¢°´´Ë˳Ðò·ÅÈëÁбí¶ÔÏó¡£ µ±Ìṩһ¸öÍƵ¼Ê½Ê±,Áбí»á¸ù¾ÝÍƵ¼Ê½Ëù²úÉúµÄ½á¹ûÔªËؽøÐй¹½¨¡£
6.2.6.?¼¯ºÏÏÔʾ
¼¯ºÏÏÔʾÊÇÓû¨À¨ºÅ±êÃ÷µÄ,Óë×ÖµäÏÔʾµÄÇø±ðÔÚÓÚûÓÐðºÅ·Ö¸ôµÄ¼üºÍÖµ:
set_display ::= "{" (starred_list | comprehension) "}"
¼¯ºÏÏÔʾ»á²úÉúÒ»¸öеĿɱ伯ºÏ¶ÔÏó,ÆäÄÚÈÝͨ¹ýһϵÁбí´ïʽ»òÒ»¸öÍƵ¼Ê½À´Ö¸¶¨¡£ µ±ÌṩÓɶººÅ·Ö¸ôµÄһϵÁбí´ïʽʱ,ÆäÔªËØ»á´Ó×óÖÁÓÒ±»ÇóÖµ²¢¼ÓÈëµ½¼¯ºÏ¶ÔÏó¡£ µ±Ìṩһ¸öÍƵ¼Ê½Ê±,¼¯ºÏ»á¸ù¾ÝÍƵ¼Ê½Ëù²úÉúµÄ½á¹ûÔªËؽøÐй¹½¨¡£
¿Õ¼¯ºÏ²»ÄÜÓÃ?{} ?À´¹¹½¨;¸Ã×ÖÃæÖµËù¹¹½¨µÄÊÇÒ»¸ö¿Õ×ֵ䡣
6.2.7.?×ÖµäÏÔʾ
×ÖµäÏÔʾÊÇÒ»¸öÓû¨À¨ºÅÀ¨ÆðÀ´µÄ¿ÉÄÜΪ¿ÕµÄ¼ü/Êý¾Ý¶ÔϵÁÐ:
dict_display ::= "{" [key_datum_list | dict_comprehension] "}"
key_datum_list ::= key_datum ("," key_datum)* [","]
key_datum ::= expression ":" expression | "**" or_expr
dict_comprehension ::= expression ":" expression comp_for
×ÖµäÏÔʾ»á²úÉúÒ»¸öеÄ×Öµä¶ÔÏó¡£
Èç¹û¸ø³öÒ»¸öÓɶººÅ·Ö¸ôµÄ¼ü/Êý¾Ý¶ÔÐòÁÐ,ËüÃÇ»á´Ó×óÖÁÓÒ±»ÇóÖµÒÔ¶¨Òå×ÖµäµÄÌõÄ¿:ÿ¸ö¼ü¶ÔÏó»á±»ÓÃ×÷ÔÚ×ÖµäÖдæ·ÅÏàÓ¦Êý¾ÝµÄ¼ü¡£ ÕâÒâζ×ÅÄã¿ÉÒÔÔÚ¼ü/Êý¾Ý¶ÔÐòÁÐÖжà´ÎÖ¸¶¨ÏàͬµÄ¼ü,×îÖÕ×ÖµäµÄÖµ½«ÓÉ×îºóÒ»´Î¸ø³öµÄ¼ü¾ö¶¨¡£
Ë«ÐǺÅ?** ?±íʾ?×Öµä²ð°ü¡£ ËüµÄ²Ù×÷Êý±ØÐëÊÇÒ»¸ö?mapping¡£ ÿ¸öÓ³ÉäÏî±»»á¼ÓÈëеÄ×ֵ䡣 ºóÐøµÄÖµ»áÌæ´úÏÈÇ°µÄ¼ü/Êý¾Ý¶ÔºÍÏÈÇ°µÄ×Öµä²ð°üËùÉèÖõÄÖµ¡£
3.5 а湦ÄÜ:?²ð°üµ½×ÖµäÏÔʾ,×î³õÓÉ?PEP 448?Ìá³ö¡£
×ÖµäÍƵ¼Ê½ÓëÁбíºÍ¼¯ºÏÍƵ¼Ê½ÓÐËù²»Í¬,ËüÐèÒªÒÔðºÅ·Ö¸ôµÄÁ½¸ö±í´ïʽ,ºóÃæ´øÉϱê×¼µÄ "for" ºÍ "if" ×Ӿ䡣 µ±ÍƵ¼Ê½±»Ö´ÐÐʱ,×÷Ϊ½á¹ûµÄ¼üºÍÖµÔªËػᰴËüÃǵIJúÉú˳Ðò±»¼ÓÈëеÄ×ֵ䡣
¶Ô¼üÈ¡ÖµÀàÐ͵ÄÏÞÖÆÒÑÁÐÔÚ֮ǰµÄ?±ê×¼ÀàÐͲ㼶½á¹¹?Ò»½ÚÖС£ (×ܵÄ˵À´,¼üµÄÀàÐÍÓ¦¸ÃΪ?hashable,Õâ¾Í°ÑËùÓпɱä¶ÔÏó¶¼ÅųýÔÚÍâ¡£) Öظ´¼üÖ®¼äµÄ³åÍ»²»»á±»¼ì²â;Ö¸¶¨¼üËù±£´æµÄ×îºóÒ»¸öÊý¾Ý (¼´ÔÚÏÔʾÖÐÅÅ×îÓұߵÄÎı¾) Ϊ×îÖÕÓÐЧÊý¾Ý¡£
ÔÚ 3.8 °æ¸ü¸Ä:?ÔÚ Python 3.8 ֮ǰµÄ×ÖµäÍƵ¼Ê½ÖÐ,²¢Ã»Óж¨ÒåºÃ¼üºÍÖµµÄÇóֵ˳Ðò¡£ ÔÚ CPython ÖÐ,Öµ»áÏÈÓÚ¼ü±»ÇóÖµ¡£ ¸ù¾Ý?PEP 572?µÄÌáÒé,´Ó 3.8 ¿ªÊ¼,¼ü»áÏÈÓÚÖµ±»ÇóÖµ¡£
6.2.8.?Éú³ÉÆ÷±í´ïʽ
Éú³ÉÆ÷±í´ïʽÊÇÓÃÔ²À¨ºÅÀ¨ÆðÀ´µÄ½ô´ÕÐÎʽÉú³ÉÆ÷±ê×¢¡£
generator_expression ::= "(" expression comp_for ")"
Éú³ÉÆ÷±í´ïʽ»á²úÉúÒ»¸öеÄÉú³ÉÆ÷¶ÔÏó¡£ Æä¾ä·¨ÓëÍƵ¼Ê½Ïàͬ,Çø±ðÔÚÓÚËüÊÇÓÃÔ²À¨ºÅ¶ø²»ÊÇÓ÷½À¨ºÅ»ò»¨À¨ºÅÀ¨ÆðÀ´µÄ¡£
ÔÚÉú³ÉÆ÷±í´ïʽÖÐʹÓõıäÁ¿»áÔÚΪÉú³ÉÆ÷¶ÔÏóµ÷ÓÃ?__next__()?·½·¨µÄʱºòÒÔ¶èÐÔ·½Ê½±»ÇóÖµ(¼´ÓëÆÕͨÉú³ÉÆ÷ÏàͬµÄ·½Ê½)¡£ µ«ÊÇ,×î×ó²à?for ?×Ó¾äÄڵĿɵü´ú¶ÔÏóÊǻᱻÁ¢¼´ÇóÖµµÄ,Òò´ËËüËùÔì³ÉµÄ´íÎó»áÔÚÉú³ÉÆ÷±í´ïʽ±»¶¨Òåʱ±»¼ì²âµ½,¶ø²»ÊÇÔÚ»ñÈ¡µÚÒ»¸öֵʱ²Å³ö´í¡£ ºóÐøµÄ?for ?×Ó¾äÒÔ¼°×î×ó²à?for ?×Ó¾äÄÚµÄÈκÎɸѡÌõ¼þÎÞ·¨ÔÚÍâ²ã×÷ÓÃÓòÄÚ±»ÇóÖµ,ÒòΪËüÃÇ¿ÉÄÜ»áÒÀÀµÓÚ´Ó×î×ó²à¿Éµü´ú¶ÔÏó»ñÈ¡µÄÖµ¡£ ÀýÈç:?(x*y?for?x?in?range(10)?for?y?in?range(x,?x+10)) .
Ô²À¨ºÅÔÚÖ»¸½´øÒ»¸ö²ÎÊýµÄµ÷ÓÃÖпÉÒÔ±»Ê¡ÂÔ¡£ ÏêÇé²Î¼û?µ÷ÓÃ?Ò»½Ú¡£
ΪÁ˱ÜÃâ¸ÉÈŵ½Éú³ÉÆ÷±í´ïʽ±¾ÉíµÄÔ¤ÆÚ²Ù×÷,½ûÖ¹ÔÚÒþʽ¶¨ÒåµÄÉú³ÉÆ÷ÖÐʹÓÃ?yield ?ºÍ?yield?from ?±í´ïʽ¡£
Èç¹ûÉú³ÉÆ÷±í´ïʽ°üº¬?async?for ?×Ó¾ä»ò?await?±í´ïʽ,Ôò³ÆΪ?Òì²½Éú³ÉÆ÷±í´ïʽ¡£ Òì²½Éú³ÉÆ÷±í´ïʽ»á·µ»ØÒ»¸öеÄÒì²½Éú³ÉÆ÷¶ÔÏó,´Ë¶ÔÏóÊôÓÚÒì²½µü´úÆ÷ (²Î¼û?Òì²½µü´úÆ÷)¡£
3.6 а湦ÄÜ:?ÒýÈëÁËÒì²½Éú³ÉÆ÷±í´ïʽ¡£
ÔÚ 3.7 °æ¸ü¸Ä:?ÔÚ Python 3.7 ֮ǰ,Òì²½Éú³ÉÆ÷±í´ïʽֻÄÜÔÚ?async?def?кÍÖгöÏÖ¡£ ´Ó 3.7 ¿ªÊ¼,Èκκ¯Êý¶¼¿ÉÒÔʹÓÃÒì²½Éú³ÉÆ÷±í´ïʽ¡£
ÔÚ 3.8 °æ¸ü¸Ä:?yield ?ºÍ?yield?from ?ÔÚÒþʽǶÌ×µÄ×÷ÓÃÓòÖÐÒѱ»½ûÓá£
6.2.9.?yield ±í´ïʽ
yield_atom ::= "(" yield_expression ")"
yield_expression ::= "yield" [expression_list | "from" expression]
The yield expression is used when defining a?generator?function or an?asynchronous generator?function and thus can only be used in the body of a function definition. Using a yield expression in a function's body causes that function to be a generator function, and using it in an?async?def?function's body causes that coroutine function to be an asynchronous generator function. For example:
def gen(): # defines a generator function
yield 123
async def agen(): # defines an asynchronous generator function
yield 123
ÓÉÓÚËüÃÇ»á¶ÔÍâ²ã×÷ÓÃÓòÔì³É¸½´øÓ°Ïì,yield ?±í´ïʽ²»±»ÔÊÐí×÷ΪÓÃÓÚʵÏÖÍƵ¼Ê½ºÍÉú³ÉÆ÷±í´ïʽµÄÒþʽ¶¨Òå×÷ÓÃÓòµÄÒ»²¿·Ö¡£
ÔÚ 3.8 °æ¸ü¸Ä:?½ûÖ¹ÔÚʵÏÖÍƵ¼Ê½ºÍÉú³ÉÆ÷±í´ïʽµÄÒþʽǶÌ××÷ÓÃÓòÖÐʹÓà yield ±í´ïʽ¡£
ÏÂÃæÊǶÔÉú³ÉÆ÷º¯ÊýµÄÃèÊö,Òì²½Éú³ÉÆ÷º¯Êý»áÔÚ?Òì²½Éú³ÉÆ÷º¯Êý?Ò»½ÚÖе¥¶À½éÉÜ¡£
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator's methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of?expression_list?to the generator's caller. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If?__next__()?is used (typically via either a?for?or the?next()?builtin) then the result is?None. Otherwise, if?send()?is used, then the result will be the value passed in to that method.
ËùÓÐÕâЩʹÉú³ÉÆ÷º¯ÊýÓëг̷dz£ÏàËÆ;ËüÃÇ yield ¶à´Î,ËüÃǾßÓжà¸öÈë¿Úµã,²¢ÇÒËüÃǵÄÖ´ÐпÉÒÔ±»¹ÒÆð¡£Î¨Ò»µÄÇø±ðÊÇÉú³ÉÆ÷º¯Êý²»ÄÜ¿ØÖÆÔÚËüÔÚ yield ºó½»¸øÄÄÀï¼ÌÐøÖ´ÐÐ;¿ØÖÆȨ×ÜÊÇתÒƵ½Éú³ÉÆ÷µÄµ÷ÓÃÕß¡£
ÔÚ?try?½á¹¹ÖеÄÈκÎλÖö¼ÔÊÐíyield±í´ïʽ¡£Èç¹ûÉú³ÉÆ÷ÔÚ(ÒòΪÒýÓüÆÊýµ½Áã»òÊÇÒòΪ±»À¬»ø»ØÊÕ)Ïú»Ù֮ǰûÓлָ´Ö´ÐÐ,½«µ÷ÓÃÉú³ÉÆ÷-µü´úÆ÷µÄ?close()?·½·¨. close ·½·¨ÔÊÐíÈκιÒÆðµÄ?finally?×Ó¾äÖ´ÐС£
µ±Ê¹ÓÃ?yield?from?<expr> ?ʱ,ËùÌṩµÄ±í´ïʽ±ØÐëÊÇÒ»¸ö¿Éµü´ú¶ÔÏó¡£ µü´ú¸Ã¿Éµü´ú¶ÔÏóËù²úÉúµÄÖµ»á±»Ö±½Ó´«µÝ¸øµ±Ç°Éú³ÉÆ÷·½·¨µÄµ÷ÓÃÕß¡£ ÈκÎͨ¹ý?send()?´«ÈëµÄÖµÒÔ¼°ÈκÎͨ¹ý?throw()?´«ÈëµÄÒì³£Èç¹ûÓÐÊʵ±µÄ·½·¨Ôò»á±»´«¸øϲãµü´úÆ÷¡£ Èç¹û²»ÊÇÕâÖÖÇé¿ö,ÄÇô?send()?½«Òý·¢?AttributeError?»ò?TypeError,¶ø?throw()?½«Á¢¼´Òý·¢ËùתÈëµÄÒì³£¡£
µ±Ï²ãµü´úÆ÷Íê³Éʱ,±»Òý·¢µÄ?StopIteration?ʵÀýµÄ?value ?ÊôÐÔ»á³ÉΪ yield ±í´ïʽµÄÖµ¡£ Ëü¿ÉÒÔÔÚÒý·¢?StopIteration?ʱ±»ÏÔʽµØÉèÖÃ,Ò²¿ÉÒÔÔÚ×Óµü´úÆ÷ÊÇÒ»¸öÉú³ÉÆ÷ʱ×Ô¶¯µØÉèÖÃ(ͨ¹ý´Ó×ÓÉú³ÉÆ÷·µ»ØÒ»¸öÖµ)¡£
ÔÚ 3.3 °æ¸ü¸Ä:?Ìí¼Ó?yield?from?<expr> ?ÒÔίÍпØÖÆÁ÷¸øÒ»¸ö×Óµü´úÆ÷¡£
µ±yield±í´ïʽÊǸ³ÖµÓï¾äÓÒ²àµÄΨһ±í´ïʽʱ,À¨ºÅ¿ÉÒÔÊ¡ÂÔ¡£
²Î¼û
PEP 255?- ¼òµ¥Éú³ÉÆ÷
ÔÚ Python ÖмÓÈëÉú³ÉÆ÷ºÍ?yield?Óï¾äµÄÌáÒé¡£
PEP 342?- ͨ¹ýÔöÇ¿ÐÍÉú³ÉÆ÷ʵÏÖгÌ
ÔöÇ¿Éú³ÉÆ÷ API ºÍÓï·¨µÄÌáÒé,ʹÆä¿ÉÒÔ±»ÓÃ×÷¼òµ¥µÄг̡£
PEP 380?- ίÍиø×ÓÉú³ÉÆ÷µÄÓï·¨
The proposal to introduce the?yield_from ?syntax, making delegation to subgenerators easy.
PEP 525?- Òì²½Éú³ÉÆ÷
ͨ¹ý¸øг̺¯Êý¼ÓÈëÉú³ÉÆ÷¹¦ÄܶÔ?PEP 492?½øÐÐÀ©Õ¹µÄÌáÒé¡£
6.2.9.1.?Éú³ÉÆ÷-µü´úÆ÷µÄ·½·¨
Õâ¸ö×ÓС½ÚÃèÊöÁËÉú³ÉÆ÷µü´úÆ÷µÄ·½·¨¡£ ËüÃǿɱ»ÓÃÓÚ¿ØÖÆÉú³ÉÆ÷º¯ÊýµÄÖ´ÐС£
Çë×¢ÒâÔÚÉú³ÉÆ÷ÒѾÔÚÖ´ÐÐʱµ÷ÓÃÒÔÏÂÈκη½·¨¶¼»áÒý·¢?ValueError?Òì³£¡£
generator.__next__()
Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a?__next__()?method, the current yield expression always evaluates to?None. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the?expression_list?is returned to?__next__()'s caller. If the generator exits without yielding another value, a?StopIteration?exception is raised.
´Ë·½·¨Í¨³£ÊÇÒþʽµØµ÷ÓÃ,ÀýÈçͨ¹ý?for?Ñ»·»òÊÇÄÚÖõÄ?next()?º¯Êý¡£
generator.send(value)
»Ö¸´Ö´Ðв¢ÏòÉú³ÉÆ÷º¯Êý¡°·¢ËÍ¡±Ò»¸öÖµ¡£?value?²ÎÊý½«³ÉΪµ±Ç° yield ±í´ïʽµÄ½á¹û¡£?send()?·½·¨»á·µ»ØÉú³ÉÆ÷Ëù²úÉúµÄÏÂÒ»¸öÖµ,»òÕßÈç¹ûÉú³ÉÆ÷ûÓвúÉúÏÂÒ»¸öÖµ¾ÍÍ˳öÔò»áÒý·¢?StopIteration¡£ µ±µ÷ÓÃ?send()?À´Æô¶¯Éú³ÉÆ÷ʱ,Ëü±ØÐëÒÔ?None?×÷Ϊµ÷ÓòÎÊý,ÒòΪÕâʱûÓпÉÒÔ½ÓÊÕÖµµÄ yield ±í´ïʽ¡£
generator.throw(value)
generator.throw(type[,?value[,?traceback]])
Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a?StopIteration?exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.
In typical use, this is called with a single exception instance similar to the way the?raise?keyword is used.
For backwards compatibility, however, the second signature is supported, following a convention from older versions of Python. The?type?argument should be an exception class, and?value?should be an exception instance. If the?value?is not provided, the?type?constructor is called to get an instance. If?traceback?is provided, it is set on the exception, otherwise any existing?__traceback__ ?attribute stored in?value?may be cleared.
generator.close()
ÔÚÉú³ÉÆ÷º¯ÊýÔÝÍ£µÄλÖÃÒý·¢?GeneratorExit¡£ Èç¹ûÖ®ºóÉú³ÉÆ÷º¯ÊýÕý³£Í˳ö¡¢¹Ø±Õ»òÒý·¢?GeneratorExit?(ÓÉÓÚ䲶»ñ¸ÃÒì³£) Ôò¹Ø±Õ²¢·µ»ØÆäµ÷ÓÃÕß¡£ Èç¹ûÉú³ÉÆ÷²úÉúÁËÒ»¸öÖµ,¹Ø±Õ»áÒý·¢?RuntimeError¡£ Èç¹ûÉú³ÉÆ÷Òý·¢ÈκÎÆäËûÒì³£,Ëü»á±»´«²¥¸øµ÷ÓÃÕß¡£ Èç¹ûÉú³ÉÆ÷ÒѾÓÉÓÚÒì³£»òÕý³£Í˳öÔò?close()?²»»á×öÈκÎÊ¡£
6.2.9.2.?Àý×Ó
ÕâÀïÊÇÒ»¸ö¼òµ¥µÄÀý×Ó,ÑÝʾÁËÉú³ÉÆ÷ºÍÉú³ÉÆ÷º¯ÊýµÄÐÐΪ:
>>>
>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... try:
... while True:
... try:
... value = (yield value)
... except Exception as e:
... value = e
... finally:
... print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
¶ÔÓÚ?yield?from ?µÄÀý×Ó, ²Î¼û¡°Python ÓÐʲôб仯¡±ÖеÄ?PEP 380: ίÍиø×ÓÉú³ÉÆ÷µÄÓï·¨¡£
6.2.9.3.?Òì²½Éú³ÉÆ÷º¯Êý
ÔÚÒ»¸öʹÓÃ?async?def?¶¨ÒåµÄº¯Êý»ò·½·¨ÖгöÏÖµÄ yield ±í´ïʽ»á½øÒ»²½½«¸Ãº¯Êý¶¨ÒåΪһ¸ö?asynchronous generator?º¯Êý¡£
µ±Ò»¸öÒì²½Éú³ÉÆ÷º¯Êý±»µ÷ÓÃʱ,Ëü»á·µ»ØÒ»¸öÃûΪÒì²½Éú³ÉÆ÷¶ÔÏóµÄÒì²½µü´úÆ÷¡£ ´Ë¶ÔÏó½«ÔÚÖ®ºó¿ØÖƸÃÉú³ÉÆ÷º¯ÊýµÄÖ´ÐС£ Òì²½Éú³ÉÆ÷¶ÔÏóͨ³£±»ÓÃÔÚг̺¯ÊýµÄ?async?for?Óï¾äÖÐ,ÀàËÆÓÚÔÚ?for?Óï¾äÖÐʹÓÃÉú³ÉÆ÷¶ÔÏó¡£
Calling one of the asynchronous generator's methods returns an?awaitable?object, and the execution starts when this object is awaited on. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of?expression_list?to the awaiting coroutine. As with a generator, suspension means that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by awaiting on the next object returned by the asynchronous generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If?__anext__()?is used then the result is?None. Otherwise, if?asend()?is used, then the result will be the value passed in to that method.
Èç¹ûÒ»¸öÒì²½Éú³ÉÆ÷Ç¡ºÃÒò?break¡¢µ÷Ó÷½ÈÎÎñ±»È¡Ïû,»òÊÇÆäËûÒì³£¶øÌáÇ°Í˳ö,Éú³ÉÆ÷µÄÒì²½ÇåÀí´úÂ뽫»áÔËÐв¢¿ÉÄÜÒý·¢Òì³£»ò·ÃÎÊÒâÍâÉÏÏÂÎÄÖеÄÉÏÏÂÎıäÁ¿ -- Ò²ÐíÊÇÔÚËüËùÒÀÀµµÄÈÎÎñµÄÉúÃüÖÜÆÚÖ®ºó,»òÊÇÔÚÒì²½Éú³ÉÆ÷À¬»ø»ØÊÕ¹³×Ó±»µ÷ÓÃʱµÄʼþÑ»·¹Ø±ÕÆڼ䡣 ΪÁË·ÀÖ¹ÕâÖÖÇé¿ö,µ÷Ó÷½±ØÐëͨ¹ýµ÷ÓÃ?aclose()?·½·¨À´ÏÔʽµØ¹Ø±ÕÒì²½Éú³ÉÆ÷ÒÔÖÕ½áÉú³ÉÆ÷²¢×îÖÕ´ÓʼþÑ»·Öн«Æä·ÖÀë¡£
ÔÚÒì²½Éú³ÉÆ÷º¯ÊýÖÐ,yield ±í´ïʽÔÊÐí³öÏÖÔÚ?try?½á¹¹µÄÈκÎλÖᣠµ«ÊÇ,Èç¹ûÒ»¸öÒì²½Éú³ÉÆ÷ÔÚÆä±»ÖÕ½á(ÓÉÓÚÒýÓüÆÊý´ïµ½Áã»ò±»×÷ΪÀ¬»ø»ØÊÕ)֮ǰδ±»»Ö¸´,Ôòthen a yield expression within a?try ?½á¹¹ÖÐµÄ yield ±í´ïʽ¿ÉÄܵ¼Ö¹ÒÆðµÄ?finally?×Ó¾äÖ´ÐÐʧ°Ü¡£ ÔÚ´ËÇé¿öÏÂ,Ó¦ÓÉÔËÐиÃÒì²½Éú³ÉÆ÷µÄʼþÑ»·»òÈÎÎñµ÷¶ÈÆ÷À´¸ºÔðµ÷ÓÃÒì²½Éú³ÉÆ÷-µü´úÆ÷µÄ?aclose()?·½·¨²¢ÔËÐÐËù·µ»ØµÄг̶ÔÏó,´Ó¶øÔÊÐíÈκιÒÆðµÄ?finally ?×Ó¾äµÃÒÔÖ´ÐС£
ΪÁËÄÜÔÚʼþÑ»·ÖÕ½áʱִÐÐ×îÖÕ»¯´¦Àí,ʼþÑ»·Ó¦µ±¶¨ÒåÒ»¸ö?ÖÕ½áÆ÷?º¯Êý,Ëü½ÓÊÜÒ»¸öÒì²½Éú³ÉÆ÷µü´úÆ÷²¢½«µ÷ÓÃ?aclose()?ÇÒÖ´ÐиÃг̡£ Õâ¸ö?ÖÕ½áÆ÷?¿ÉÒÔͨ¹ýµ÷ÓÃ?sys.set_asyncgen_hooks()?À´×¢²á¡£ µ±Ê״εü´úʱ,Òì²½Éú³ÉÆ÷µü´úÆ÷½«±£´æÒÑ×¢²áµÄ?ÖÕ½áÆ÷?ÒÔ±ãÔÚ×îÖÕ»¯Ê±µ÷ÓᣠÓйØ?ÖÕ½áÆ÷?·½·¨µÄ²Î¿¼Ê¾ÀýÇë²é¿´ÔÚ?Lib/asyncio/base_events.py?µÄÖеÄ?asyncio.Loop.shutdown_asyncgens ?ʵÏÖ¡£
yield?from?<expr> ?±í´ïʽÈç¹ûÔÚÒì²½Éú³ÉÆ÷º¯ÊýÖÐʹÓûáÒý·¢Óï·¨´íÎó¡£
6.2.9.4.?Òì²½Éú³ÉÆ÷-µü´úÆ÷·½·¨
Õâ¸ö×ÓС½ÚÃèÊöÁËÒì²½Éú³ÉÆ÷µü´úÆ÷µÄ·½·¨,ËüÃǿɱ»ÓÃÓÚ¿ØÖÆÉú³ÉÆ÷º¯ÊýµÄÖ´ÐС£
coroutine?agen.__anext__()
Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an?__anext__()?method, the current yield expression always evaluates to?None?in the returned awaitable, which when run will continue to the next yield expression. The value of the?expression_list?of the yield expression is the value of the?StopIteration?exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a?StopAsyncIteration?exception, signalling that the asynchronous iteration has completed.
´Ë·½·¨Í¨³£ÊÇͨ¹ý?async?for?Ñ»·ÒþʽµØµ÷Óá£
coroutine?agen.asend(value)
·µ»ØÒ»¸ö¿ÉµÈ´ý¶ÔÏó,ËüÔÚÔËÐÐʱ»á»Ö¸´¸ÃÒì²½Éú³ÉÆ÷µÄÖ´ÐС£ ÓëÉú³ÉÆ÷µÄ?send()?·½·¨Ò»Ñù,´Ë·½·¨»á¡°·¢ËÍ¡±Ò»¸öÖµ¸øÒì²½Éú³ÉÆ÷º¯Êý,Æä?value?²ÎÊý»á³ÉΪµ±Ç° yield ±í´ïʽµÄ½á¹ûÖµ¡£?asend()?·½·¨Ëù·µ»ØµÄ¿ÉµÈ´ý¶ÔÏ󽫷µ»ØÉú³ÉÆ÷²úÉúµÄÏÂÒ»¸öÖµ,ÆäֵΪËùÒý·¢µÄ?StopIteration,»òÕßÈç¹ûÒì²½Éú³ÉÆ÷ûÓвúÉúÏÂÒ»¸öÖµ¾ÍÍ˳öÔòÒý·¢?StopAsyncIteration¡£ µ±µ÷ÓÃ?asend()?À´Æô¶¯Òì²½Éú³ÉÆ÷ʱ,Ëü±ØÐëÒÔ?None?×÷Ϊµ÷ÓòÎÊý,ÒòΪÕâʱûÓпÉÒÔ½ÓÊÕÖµµÄ yield ±í´ïʽ¡£
coroutine?agen.athrow(type[,?value[,?traceback]])
·µ»ØÒ»¸ö¿ÉµÈ´ý¶ÔÏó,Ëü»áÔÚÒì²½Éú³ÉÆ÷ÔÝÍ£µÄλÖÃÒý·¢?type ?ÀàÐ͵ÄÒì³£,²¢·µ»Ø¸ÃÉú³ÉÆ÷º¯ÊýËù²úÉúµÄÏÂÒ»¸öÖµ,ÆäֵΪËùÒý·¢µÄ?StopIteration?Òì³£¡£ Èç¹ûÒì²½Éú³ÉÆ÷ûÓвúÉúÏÂÒ»¸öÖµ¾ÍÍ˳ö,Ôò½«Óɸÿɵȴý¶ÔÏóÒý·¢?StopAsyncIteration?Òì²½¡£ Èç¹ûÉú³ÉÆ÷º¯ÊýûÓⶻñ´«ÈëµÄÒì³£,»òÒý·¢ÁËÁíÒ»¸öÒì³£,Ôòµ±¿ÉµÈ´ý¶ÔÏóÔËÐÐʱ¸ÃÒì³£»á±»´«²¥¸ø¿ÉµÈ´ý¶ÔÏóµÄµ÷ÓÃÕß¡£
coroutine?agen.aclose()
·µ»ØÒ»¸ö¿ÉµÈ´ý¶ÔÏó,Ëü»áÔÚÔËÐÐʱÏòÒì²½Éú³ÉÆ÷º¯ÊýÔÝÍ£µÄλÖÃÅ×ÈëÒ»¸ö?GeneratorExit¡£ Èç¹û¸ÃÒì²½Éú³ÉÆ÷º¯ÊýÕý³£Í˳ö¡¢¹Ø±Õ»òÒý·¢?GeneratorExit?(ÓÉÓÚ䲶»ñ¸ÃÒì³£) Ôò·µ»ØµÄ¿ÉµÈ´ý¶ÔÏó½«Òý·¢?StopIteration?Òì³£¡£ ºóÐøµ÷ÓÃÒì²½Éú³ÉÆ÷Ëù·µ»ØµÄÈκÎÆäËû¿ÉµÈ´ý¶ÔÏó½«Òý·¢?StopAsyncIteration?Òì³£¡£ Èç¹ûÒì²½Éú³ÉÆ÷²úÉúÁËÒ»¸öÖµ,¸Ã¿ÉµÈ´ý¶ÔÏó»áÒý·¢?RuntimeError¡£ Èç¹ûÒì²½Éú³ÉÆ÷Òý·¢ÈκÎÆäËûÒì³£,Ëü»á±»´«²¥¸ø¿ÉµÈ´ý¶ÔÏóµÄµ÷ÓÃÕß¡£ Èç¹ûÒì²½Éú³ÉÆ÷ÒѾÓÉÓÚÒì³£»òÕý³£Í˳öÔòºóÐøµ÷ÓÃ?aclose()?½«·µ»ØÒ»¸ö²»»á×öÈκÎʵĿɵȴý¶ÔÏó¡£
6.3.?ÔÐÍ
ÔÐÍ´ú±í±à³ÌÓïÑÔÖÐ×î½ôÃܰ󶨵IJÙ×÷¡£ ËüÃǵľ䷨ÈçÏÂ:
primary ::= atom | attributeref | subscription | slicing | call
6.3.1.?ÊôÐÔÒýÓÃ
ÊôÐÔÒýÓÃÊǺóÃæ´øÓÐÒ»¸ö¾äµã¼ÓÒ»¸öÃû³ÆµÄÔÐÍ:
attributeref ::= primary "." identifier
´ËÔÐͱØÐëÇóֵΪһ¸öÖ§³ÖÊôÐÔÒýÓõÄÀàÐ͵ĶÔÏó,¶àÊý¶ÔÏó¶¼Ö§³ÖÊôÐÔÒýÓᣠËæºó¸Ã¶ÔÏó»á±»ÒªÇó²úÉúÒÔÖ¸¶¨±êʶ·ûΪÃû³ÆµÄÊôÐÔ¡£ Õâ¸ö²úÉú¹ý³Ì¿Éͨ¹ýÖØÔØ?__getattr__() ?·½·¨À´×Ô¶¨Òå¡£ Èç¹ûÕâ¸öÊôÐÔ²»¿ÉÓÃ,Ôò½«Òý·¢?AttributeError?Òì³£¡£ ·ñÔòµÄ»°,Ëù²úÉú¶ÔÏóµÄÀàÐͺÍÖµ»á¸ù¾Ý¸Ã¶ÔÏóÀ´È·¶¨¡£ ¶ÔͬһÊôÐÔÒýÓõĶà´ÎÇóÖµ¿ÉÄܲúÉú²»Í¬µÄ¶ÔÏó¡£
6.3.2.?³éÈ¡
The subscription of an instance of a?container class?will generally select an element from the container. The subscription of a?generic class?will generally return a?GenericAlias?object.
subscription ::= primary "[" expression_list "]"
When an object is subscripted, the interpreter will evaluate the primary and the expression list.
The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of?__getitem__()?and?__class_getitem__(). When the primary is subscripted, the evaluated result of the expression list will be passed to one of these methods. For more details on when?__class_getitem__ ?is called instead of?__getitem__ , see?__class_getitem__ versus __getitem__.
If the expression list contains at least one comma, it will evaluate to a?tuple?containing the items of the expression list. Otherwise, the expression list will evaluate to the value of the list's sole member.
For built-in objects, there are two types of objects that support subscription via?__getitem__():
-
Mappings. If the primary is a?mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. An example of a builtin mapping class is the?dict?class. -
Sequences. If the primary is a?sequence, the expression list must evaluate to an?int?or a?slice?(as discussed in the following section). Examples of builtin sequence classes include the?str,?list?and?tuple?classes.
The formal syntax makes no special provision for negative indices in?sequences. However, built-in sequences all provide a?__getitem__()?method that interprets negative indices by adding the length of the sequence to the index so that, for example,?x[-1] ?selects the last item of?x . The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). Since the support for negative indices and slicing occurs in the object's?__getitem__() ?method, subclasses overriding this method will need to explicitly add that support.
A?string?is a special kind of sequence whose items are?characters. A character is not a separate data type but a string of exactly one character.
6.3.3.?ÇÐƬ
ÇÐƬ¾ÍÊÇÔÚÐòÁжÔÏó(×Ö·û´®¡¢Ôª×é»òÁбí)ÖÐÑ¡Ôñij¸ö·¶Î§ÄÚµÄÏî¡£ ÇÐƬ¿É±»ÓÃ×÷±í´ïʽÒÔ¼°¸³Öµ»ò?del?Óï¾äµÄÄ¿±ê¡£ ÇÐƬµÄ¾ä·¨ÈçÏÂ:
slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
´Ë´¦µÄÕýʽ¾ä·¨ÖдæÔÚÒ»µãÆçÒå:ÈκÎÐÎËƱí´ïʽÁбíµÄ¶«Î÷ͬÑùÒ²»áÐÎËÆÇÐƬÁбí,Òò´ËÈκγéÈ¡²Ù×÷Ò²¿ÉÒÔ±»½âÎöΪÇÐƬ¡£ ΪÁ˲»Ê¹¾ä·¨¸ü¼Ó¸´ÔÓ,ÓÚÊÇͨ¹ý¶¨Ò彫´ËÇé¿ö½âÎöΪ³éÈ¡ÓÅÏÈÓÚ½âÎöΪÇÐƬÀ´Ïû³ýÕâÖÖÆçÒå(ÇÐƬÁбíδ°üº¬ÕýÈ·µÄÇÐƬ¾ÍÊôÓÚ´ËÇé¿ö)¡£
ÇÐƬµÄÓïÒåÈçÏÂËùÊö¡£ ÔªÐÍͨ¹ýÒ»¸ö¸ù¾ÝÏÂÃæµÄÇÐƬÁбíÀ´¹¹ÔìµÄ¼ü½øÐÐË÷Òý(ÓëÆÕͨ³éÈ¡Ò»ÑùʹÓÃ?__getitem__() ?·½·¨)¡£ Èç¹ûÇÐƬÁбí°üº¬ÖÁÉÙÒ»¸ö¶ººÅ,Ôò¼ü½«ÊÇÒ»¸ö°üº¬ÇÐƬÏîת»»µÄÔª×é;·ñÔòµÄ»°,¼ü½«Êǵ¥¸öÇÐƬÏîµÄת»»¡£ ÇÐƬÏîÈçΪһ¸ö±í´ïʽ,ÔòÆäת»»¾ÍÊǸñí´ïʽ¡£ Ò»¸öÕýÈ·ÇÐƬµÄת»»¾ÍÊÇÒ»¸öÇÐƬ¶ÔÏó(²Î¼û?±ê×¼ÀàÐͲ㼶½á¹¹?Ò»½Ú),¸Ã¶ÔÏóµÄ?start ,?stop ?ºÍ?step ?ÊôÐÔ½«·Ö±ðΪ±í´ïʽËù¸ø³öµÄϽ硢ÉϽçºÍ²½³¤Öµ,Ê¡ÂԵıí´ïʽ½«ÓÃ?None ?À´Ìæ»»¡£
6.3.4.?µ÷ÓÃ
Ëùνµ÷ÓþÍÊǸ½´ø¿ÉÄÜΪ¿ÕµÄһϵÁÐ?²ÎÊý?À´Ö´ÐÐÒ»¸ö¿Éµ÷ÓöÔÏó (ÀýÈç?function):
call ::= primary "(" [argument_list [","] | comprehension] ")"
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
positional_arguments ::= positional_item ("," positional_item)*
positional_item ::= assignment_expression | "*" expression
starred_and_keywords ::= ("*" expression | keyword_item)
("," "*" expression | "," keyword_item)*
keywords_arguments ::= (keyword_item | "**" expression)
("," keyword_item | "," "**" expression)*
keyword_item ::= identifier "=" expression
Ò»¸ö¿ÉÑ¡ÏîΪÔÚλÖú͹ؼü×Ö²ÎÊýºó¼ÓÉ϶ººÅ¶ø²»Ó°ÏìÓïÒå¡£
´ËÔÐͱØÐëÇóֵΪһ¸ö¿Éµ÷ÓöÔÏó(Óû§¶¨ÒåµÄº¯Êý,ÄÚÖú¯Êý,ÄÚÖöÔÏóµÄ·½·¨,Àà¶ÔÏó,ÀàʵÀýµÄ·½·¨ÒÔ¼°ÈκξßÓÐ?__call__() ?·½·¨µÄ¶ÔÏó¶¼Êǿɵ÷ÓöÔÏó)¡£ ËùÓвÎÊý±í´ïʽ½«ÔÚ³¢ÊÔµ÷ÓÃÇ°±»ÇóÖµ¡£ Çë²ÎÔÄ?º¯Êý¶¨Òå?Ò»½ÚÁ˽âÕýʽµÄ?parameter?Áбí¾ä·¨¡£
If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a?TypeError?exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is?None , it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a?TypeError?exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.
CPython implementation detail:?ijЩʵÏÖ¿ÉÄÜÌṩλÖòÎÊýûÓÐÃû³ÆµÄÄÚÖú¯Êý,¼´Ê¹ËüÃÇÔÚÎĵµËµÃ÷µÄ³¡ºÏÏÂÓС°ÃüÃû¡±,Òò´Ë²»ÄÜÒԹؼü×ÖÐÎʽÌṩ²ÎÊý¡£ ÔÚ CPython ÖÐ,ÒÔ C ±àд²¢Ê¹ÓÃ?PyArg_ParseTuple()?À´½âÎöÆä²ÎÊýµÄº¯ÊýʵÏÖ¾ÍÊôÓÚÕâÖÖÇé¿ö¡£
Èç¹û´æÔÚ±ÈÕýʽ²ÎÊý¿Õλ¶àµÄλÖòÎÊý,½«»áÒý·¢?TypeError?Òì³£,³ý·ÇÓÐÒ»¸öÕýʽ²ÎÊýʹÓÃÁË?*identifier ?¾ä·¨;ÔÚ´ËÇé¿öÏÂ,¸ÃÕýʽ²ÎÊý½«½ÓÊÜÒ»¸ö°üº¬Á˶àÓàλÖòÎÊýµÄÔª×é(Èç¹ûûÓжàÓàλÖòÎÊýÔòΪһ¸ö¿ÕÔª×é)¡£
Èç¹ûÈκιؼü×Ö²ÎÊýûÓÐÓëÖ®¶ÔÓ¦µÄÕýʽ²ÎÊýÃû³Æ,½«»áÒý·¢?TypeError?Òì³£,³ý·ÇÓÐÒ»¸öÕýʽ²ÎÊýʹÓÃÁË?**identifier ?¾ä·¨,¸ÃÕýʽ²ÎÊý½«½ÓÊÜÒ»¸ö°üº¬Á˶àÓà¹Ø¼ü×Ö²ÎÊýµÄ×Öµä(ʹÓùؼü×Ö×÷Ϊ¼ü¶ø²ÎÊýÖµ×÷ΪÓë¼ü¶ÔÓ¦µÄÖµ),Èç¹ûûÓжàÓà¹Ø¼ü×Ö²ÎÊýÔòΪһ¸ö(еÄ)¿Õ×ֵ䡣
Èç¹ûº¯Êýµ÷ÓÃÖгöÏÖÁË?*expression ?¾ä·¨,expression ?±ØÐëÇóֵΪһ¸ö?iterable¡£ À´×Ըÿɵü´ú¶ÔÏóµÄÔªËػᱻµ±×÷ÊǶîÍâµÄλÖòÎÊý¡£ ¶ÔÓÚ?f(x1,?x2,?*y,?x3,?x4) ?µ÷ÓÃ,Èç¹û?y?ÇóֵΪһ¸öÐòÁÐ?y1, ...,?yM,ÔòËü¾ÍµÈ¼ÛÓÚÒ»¸ö´øÓÐ M+4 ¸öλÖòÎÊý?x1,?x2,?y1, ...,?yM,?x3,?x4?µÄµ÷Óá£
ÕâÑù×öµÄÒ»¸öºó¹ûÊÇËäÈ»?*expression ?¾ä·¨¿ÉÄܳöÏÖÓÚÏÔʽµÄ¹Ø¼ü×Ö²ÎÊý?Ö®ºó,µ«Ëü»áÔڹؼü×Ö²ÎÊý(ÒÔ¼°ÈκÎ?**expression ?²ÎÊý -- ¼ûÏÂÎÄ)?֮ǰ?±»´¦Àí¡£ Òò´Ë:
>>>
>>> def f(a, b):
... print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
It is unusual for both keyword arguments and the?*expression ?syntax to be used in the same call, so in practice this confusion does not often arise.
Èç¹ûº¯Êýµ÷ÓÃÖгöÏÖÁË?**expression ?¾ä·¨,expression ?±ØÐëÇóֵΪһ¸ö?mapping,ÆäÄÚÈݻᱻµ±×÷ÊǶîÍâµÄ¹Ø¼ü×Ö²ÎÊý¡£ Èç¹ûÒ»¸ö¹Ø¼ü×ÖÒÑ´æÔÚ(×÷ΪÏÔʽ¹Ø¼ü×Ö²ÎÊý,»òÀ´×ÔÁíÒ»¸ö²ð°ü),Ôò½«Òý·¢?TypeError?Òì³£¡£
ʹÓÃ?*identifier ?»ò?**identifier ?¾ä·¨µÄÕýʽ²ÎÊý²»Äܱ»ÓÃ×÷λÖòÎÊý¿Õλ»ò¹Ø¼ü×Ö²ÎÊýÃû³Æ¡£
ÔÚ 3.5 °æ¸ü¸Ä:?º¯Êýµ÷ÓýÓÊÜÈÎÒâÊýÁ¿µÄ?* ?ºÍ?** ?²ð°ü,λÖòÎÊý¿ÉÄܸúÔڿɵü´ú¶ÔÏó²ð°ü (* ) Ö®ºó,¶ø¹Ø¼ü×Ö²ÎÊý¿ÉÄܸúÔÚ×Öµä²ð°ü (** ) Ö®ºó¡£ ÓÉ?PEP 448?·¢Æð×î³õÌáÒé¡£
³ý·ÇÒý·¢ÁËÒì³£,µ÷ÓÃ×ÜÊÇ»áÓзµ»ØÖµ,·µ»ØÖµÒ²¿ÉÄÜΪ?None ¡£ ·µ»ØÖµµÄ¼ÆË㷽ʽȡ¾öÓڿɵ÷ÓöÔÏóµÄÀàÐÍ¡£
Èç¹ûÀàÐÍΪ---
Óû§×Ô¶¨Ò庯Êý:
º¯ÊýµÄ´úÂë¿é»á±»Ö´ÐÐ,²¢ÏòÆä´«Èë²ÎÊýÁÐ±í¡£ ´úÂë¿éËù×öµÄµÚÒ»¼þÊÂÊǽ«ÕýʽÐβΰ󶨵½¶ÔÓ¦²ÎÊý;Ïà¹ØÃèÊö²Î¼û?º¯Êý¶¨Òå?Ò»½Ú¡£ µ±´úÂë¿éÖ´ÐÐ?return?Óï¾äʱ,ÓÉÆäÖ¸¶¨º¯Êýµ÷Óõķµ»ØÖµ¡£
ÄÚÖú¯Êý»ò·½·¨:
¾ßÌå½á¹ûÒÀÀµÓÚ½âÊÍÆ÷;ÓйØÄÚÖú¯ÊýºÍ·½·¨µÄÃèÊö²Î¼û?ÄÚÖú¯Êý¡£
Àà¶ÔÏó:
·µ»Ø¸ÃÀàµÄÒ»¸öÐÂʵÀý¡£
ÀàʵÀý·½·¨:
µ÷ÓÃÏàÓ¦µÄÓû§×Ô¶¨Ò庯Êý,ÏòÆä´«ÈëµÄ²ÎÊýÁбí»á±Èµ÷ÓõIJÎÊýÁбí¶àÒ»Ïî:¸ÃʵÀý½«³ÉΪµÚÒ»¸ö²ÎÊý¡£
ÀàʵÀý:
¸ÃÀà±ØÐ붨ÒåÓÐ?__call__() ?·½·¨;×÷ÓÃЧ¹û½«µÈ¼ÛÓÚµ÷Óø÷½·¨¡£
6.4.?await ±í´ïʽ
¹ÒÆð?coroutine?µÄÖ´ÐÐÒԵȴýÒ»¸ö?awaitable?¶ÔÏó¡£ Ö»ÄÜÔÚ?coroutine function?ÄÚ²¿Ê¹Óá£
await_expr ::= "await" primary
3.5 а湦ÄÜ.
6.5.?ÃÝÔËËã·û
ÃÝÔËËã·ûµÄ°ó¶¨±ÈÔÚÆä×ó²àµÄÒ»ÔªÔËËã·û¸ü½ôÃÜ;µ«°ó¶¨½ôÃ̶ܳȲ»¼°ÔÚÆäÓÒ²àµÄÒ»ÔªÔËËã·û¡£ ¾ä·¨ÈçÏÂ:
power ::= (await_expr | primary) ["**" u_expr]
Òò´Ë,ÔÚÒ»¸öδ¼ÓÔ²À¨ºÅµÄÃÝÔËËã·ûºÍµ¥Ä¿ÔËËã·ûÐòÁÐÖÐ,ÔËËã·û½«´ÓÓÒÏò×óÇóÖµ(Õâ²»»áÏÞÖƲÙ×÷ÊýµÄÇóֵ˳Ðò):?-1**2 ?½á¹û½«Îª?-1 ¡£
ÃÝÔËËã·ûÓ븽´øÁ½¸ö²ÎÊýµ÷ÓÃÄÚÖÃ?pow()?º¯Êý¾ßÓÐÏàͬµÄÓïÒå:½á¹ûΪ¶ÔÆä×ó²ÎÊý½øÐÐÆäÓÒ²ÎÊýËùÖ¸¶¨Ãݴεij˷½ÔËËã¡£ ÊýÖµ²ÎÊý»áÏÈת»»ÎªÏàͬÀàÐÍ,½á¹ûҲΪת»»ºóµÄÀàÐÍ¡£
¶ÔÓÚ int ÀàÐ͵IJÙ×÷Êý,½á¹û½«¾ßÓÐÓë²Ù×÷ÊýÏàͬµÄÀàÐÍ,³ý·ÇµÚ¶þ¸ö²ÎÊýΪ¸ºÊý;ÔÚÄÇÖÖÇé¿öÏÂ,ËùÓвÎÊý»á±»×ª»»Îª float ÀàÐͲ¢Êä³ö float ÀàÐ͵Ľá¹û¡£ ÀýÈç,10**2 ?·µ»Ø?100 ,¶ø?10**-2 ?·µ»Ø?0.01 ¡£
¶Ô?0.0 ?½øÐиºÊýÃÝ´ÎÔËË㽫µ¼ÖÂ?ZeroDivisionError¡£ ¶Ô¸ºÊý½øÐзÖÊýÃÝ´ÎÔËË㽫·µ»Ø?complex?ÊýÖµ¡£ (ÔÚÔçÆÚ°æ±¾ÖÐÕ⽫Òý·¢?ValueError¡£)
´ËÔËËã·û¿ÉʹÓÃÌØÊâµÄ?__pow__() ?·½·¨À´×Ô¶¨Òå¡£
6.6.?Ò»ÔªËãÊõºÍλÔËËã
ËùÓÐËãÊõºÍλÔËËã¾ßÓÐÏàͬµÄÓÅÏȼ¶:
u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr
Ò»ÔªµÄ?- ?(¸ºÖµ) ÔËËã·û»á²úÉúÆäÊý×Ö²ÎÊýµÄ¸ºÖµ;¸ÃÔËËã¿Éͨ¹ý?__neg__() ?ÌØÊâ·½·¨À´ÖØÔØ¡£
Ò»ÔªµÄ?+ ?(ÕýÖµ) ÔËËã·û»áÔÑùÊä³öÆäÊý×Ö²ÎÊý;¸ÃÔËËã¿Éͨ¹ý?__pos__() ?ÌØÊâ·½·¨À´ÖØÔØ¡£
Ò»ÔªµÄ?~ ?(È¡·´) ÔËËã·û»á¶ÔÆäÕûÊý²ÎÊý°´Î»È¡·´¡£?x ?µÄ°´Î»È¡·´±»¶¨ÒåΪ?-(x+1) ¡£ ËüÖ»×÷ÓÃÓÚÕûÊý»òÊÇÖØÔØÁË?__invert__() ?ÌØÊâ·½·¨µÄ×Ô¶¨Òå¶ÔÏó¡£
ÔÚËùÓÐÈýÖÖÇé¿öÏÂ,Èç¹û²ÎÊýµÄÀàÐͲ»ÕýÈ·,½«Òý·¢?TypeError?Òì³£¡£
6.7.?¶þÔªËãÊõÔËËã·û
¶þÔªËãÊõÔËËã·û×ñÑ´«Í³µÄÓÅÏȼ¶¡£ Çë×¢ÒâijЩ´ËÀàÔËËã·ûÒ²×÷ÓÃÓÚÌض¨µÄ·ÇÊý×ÖÀàÐÍ¡£ ³ýÃÝÔËËã·ûÒÔÍâÖ»ÓÐÁ½¸öÓÅÏȼ¶±ð,Ò»¸ö×÷ÓÃÓڳ˷¨ÐÍÔËËã·û,ÁíÒ»¸ö×÷ÓÃÓÚ¼Ó·¨ÐÍÔËËã·û:
m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
m_expr "//" u_expr | m_expr "/" u_expr |
m_expr "%" u_expr
a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr
ÔËËã·û?* ?(³Ë) ½«Êä³öÆä²ÎÊýµÄ³Ë»ý¡£ Á½¸ö²ÎÊý»òÕß±ØÐ붼ΪÊý×Ö,»òÕßÒ»¸ö²ÎÊý±ØÐëΪÕûÊý¶øÁíÒ»¸ö²ÎÊý±ØÐëΪÐòÁС£ ÔÚÇ°Ò»ÖÖÇé¿öÏÂ,Á½¸öÊý×Ö½«±»×ª»»ÎªÏàͬÀàÐÍÈ»ºóÏà³Ë¡£ ÔÚºóÒ»ÖÖÇé¿öÏÂ,½«Ö´ÐÐÐòÁеÄÖظ´;Öظ´Òò×ÓΪ¸ºÊý½«Êä³ö¿ÕÐòÁС£
´ËÔËËã¿ÉʹÓÃÌØÊâµÄ?__mul__() ?ºÍ?__rmul__() ?·½·¨À´×Ô¶¨Òå¡£
ÔËËã·û?@ ?(at) µÄÄ¿±êÊÇÓÃÓÚ¾ØÕó³Ë·¨¡£ ûÓÐÄÚÖà Python ÀàÐÍʵÏÖ´ËÔËËã·û¡£
3.5 а湦ÄÜ.
ÔËËã·û?/ ?(³ý) ºÍ?// ?(Õû³ý) ½«Êä³öÆä²ÎÊýµÄÉÌ¡£ Á½¸öÊý×Ö²ÎÊý½«Ïȱ»×ª»»ÎªÏàͬÀàÐÍ¡£ ÕûÊýÏà³ý»áÊä³öÒ»¸ö float Öµ,ÕûÊýÏàÕû³ýµÄ½á¹ûÈÔÊÇÕûÊý;Õû³ýµÄ½á¹û¾ÍÊÇʹÓà 'floor' º¯Êý½øÐÐËãÊõ³ý·¨µÄ½á¹û¡£ ³ýÒÔÁãµÄÔËË㽫Òý·¢?ZeroDivisionError?Òì³£¡£
This operation can be customized using the special?__truediv__() ?and?__floordiv__() ?methods.
ÔËËã·û?% ?(Ä£) ½«Êä³öµÚÒ»¸ö²ÎÊý³ýÒÔµÚ¶þ¸ö²ÎÊýµÄÓàÊý¡£ Á½¸öÊý×Ö²ÎÊý½«Ïȱ»×ª»»ÎªÏàͬÀàÐÍ¡£ ÓÒ²ÎÊýΪÁ㽫Òý·¢?ZeroDivisionError?Òì³£¡£ ²ÎÊý¿ÉÒÔΪ¸¡µãÊý,ÀýÈç?3.14%0.7 ?µÈÓÚ?0.34 ?(ÒòΪ?3.14 ?µÈÓÚ?4*0.7?+?0.34 )¡£ Ä£ÔËËã·ûµÄ½á¹ûµÄÕý¸º×ÜÊÇÓëµÚ¶þ¸ö²Ù×÷ÊýÒ»ÖÂ(»òÊÇΪÁã);½á¹ûµÄ¾ø¶ÔÖµÒ»¶¨Ð¡ÓÚµÚ¶þ¸ö²Ù×÷ÊýµÄ¾ø¶ÔÖµ?1¡£
Õû³ýÓëÄ£ÔËËã·ûµÄÁªÏµ¿Éͨ¹ýÒÔϵÈʽ˵Ã÷:?x?==?(x//y)*y?+?(x%y) ¡£ ´ËÍâÕû³ýÓëÄ£Ò²¿Éͨ¹ýÄÚÖú¯Êý?divmod()?À´Í¬Ê±½øÐÐ:?divmod(x,?y)?==?(x//y,?x%y) ¡£?2¡£
³ýÁ˶ÔÊý×ÖÖ´ÐÐÄ£ÔËËã,ÔËËã·û?% ?»¹±»×Ö·û´®¶ÔÏóÖØÔØÓÃÓÚÖ´ÐоÉʽµÄ×Ö·û´®¸ñʽ»¯(ÓֳƲåÖµ)¡£ ×Ö·û´®¸ñʽ»¯¾ä·¨µÄÃèÊö²Î¼û Python ¿â²Î¿¼µÄ?printf ·ç¸ñµÄ×Ö·û´®¸ñʽ»¯?Ò»½Ú¡£
È¡Óà?ÔËËã¿ÉʹÓÃÌØÊâµÄ?__mod__() ?·½·¨À´×Ô¶¨Òå¡£
Õû³ýÔËËã·û,Ä£ÔËËã·ûºÍ?divmod()?º¯Êýδ±»¶¨ÒåÓÃÓÚ¸´Êý¡£ Èç¹ûÓбØÒª¿ÉÒÔʹÓÃ?abs()?º¯Êý½«Æäת»»Îª¸¡µãÊý¡£
ÔËËã·û?+ ?(addition) ½«Êä³öÆä²ÎÊýµÄºÍ¡£ Á½¸ö²ÎÊý»òÕß±ØÐ붼ΪÊý×Ö,»òÕ߶¼ÎªÏàͬÀàÐ͵ÄÐòÁС£ ÔÚÇ°Ò»ÖÖÇé¿öÏÂ,Á½¸öÊý×Ö½«±»×ª»»ÎªÏàͬÀàÐÍÈ»ºóÏà¼Ó¡£ ÔÚºóÒ»ÖÖÇé¿öÏÂ,½«Ö´ÐÐÐòÁÐÆ´½Ó²Ù×÷¡£
´ËÔËËã¿ÉʹÓÃÌØÊâµÄ?__add__() ?ºÍ?__radd__() ?·½·¨À´×Ô¶¨Òå¡£
ÔËËã·û?- ?(¼õ) ½«Êä³öÆä²ÎÊýµÄ²î¡£ Á½¸öÊý×Ö²ÎÊý½«Ïȱ»×ª»»ÎªÏàͬÀàÐÍ¡£
´ËÔËËã¿ÉʹÓÃÌØÊâµÄ?__sub__() ?·½·¨À´×Ô¶¨Òå¡£
6.8.?ÒÆλÔËËã
ÒÆλÔËËãµÄÓÅÏȼ¶µÍÓÚËãÊõÔËËã:
shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr
ÕâЩÔËËã·û½ÓÊÜÕûÊý²ÎÊý¡£ ËüÃǻὫµÚÒ»¸ö²ÎÊý×óÒÆ»òÓÒÒƵڶþ¸ö²ÎÊýËùÖ¸¶¨µÄ±ÈÌØλÊý¡£
´ËÔËËã¿ÉʹÓÃÌØÊâµÄ?__lshift__() ?ºÍ?__rshift__() ?·½·¨À´×Ô¶¨Òå¡£
ÓÒÒÆ?n?λ±»¶¨ÒåΪ±»?pow(2,n) ?Õû³ý¡£ ×óÒÆ?n?λ±»¶¨ÒåΪ³ËÒÔ?pow(2,n) ¡£
6.9.?¶þԪλÔËËã
ÈýÖÖλÔËËã¾ßÓи÷²»ÏàͬµÄÓÅÏȼ¶:
and_expr ::= shift_expr | and_expr "&" shift_expr
xor_expr ::= and_expr | xor_expr "^" and_expr
or_expr ::= xor_expr | or_expr "|" xor_expr
& ?ÔËËã·û»á¶ÔÆä²ÎÊýÖ´Ðа´Î» AND,²ÎÊý±ØÐ붼ΪÕûÊý»òÕßÆäÖÐÖ®Ò»±ØÐëΪÖØÔØÁË?__and__() ?»ò?__rand__() ?ÌØÊâ·½·¨µÄ×Ô¶¨Òå¶ÔÏó¡£
^ ?ÔËËã·û»á¶ÔÆä²ÎÊýÖ´Ðа´Î» XOR (Òì OR),²ÎÊý±ØÐ붼ΪÕûÊý»òÕßÆäÖÐÖ®Ò»±ØÐëΪÖØÔØÁË?__xor__() ?»ò?__rxor__() ?ÌØÊâ·½·¨µÄ×Ô¶¨Òå¶ÔÏó¡£
| ?ÔËËã·û»á¶ÔÆä²ÎÊýÖ´Ðа´Î» (ºÏ²¢) OR,²ÎÊý±ØÐ붼ΪÕûÊý»òÕßÆäÖÐÖ®Ò»±ØÐëΪÖØÔØÁË?__or__() ?»ò?__ror__() ?ÌØÊâ·½·¨µÄ×Ô¶¨Òå¶ÔÏó¡£
6.10.?±È½ÏÔËËã
Óë C ²»Í¬,Python ÖÐËùÓбȽÏÔËËãµÄÓÅÏȼ¶Ïàͬ,µÍÓÚÈκÎËãÊõ¡¢ÒÆλ»òλÔËËã¡£ ÁíÒ»¸öÓë C ²»Í¬Ö®´¦ÔÚÓÚ?a?<?b?<?c ?ÕâÑùµÄ±í´ïʽ»á°´´«Í³ËãÊõ·¨ÔòÀ´½â¶Á:
comparison ::= or_expr (comp_operator or_expr)*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
±È½ÏÔËËã»á²úÉú²¼¶ûÖµ:?True ?»ò?False ¡£ ×Ô¶¨ÒåµÄ?¸»±È½Ï·½·¨?¿ÉÄÜ·µ»Ø·Ç²¼¶ûÖµ¡£ ÔÚ´ËÇé¿öÏ Python ½«ÔÚ²¼¶ûÔËËãÉÏÏÂÎÄÖжԸÃÖµµ÷ÓÃ?bool()¡£
±È½ÏÔËËã¿ÉÒÔÈÎÒâ´®Á¬,ÀýÈç?x?<?y?<=?z ?µÈ¼ÛÓÚ?x?<?y?and?y?<=?z ,³ýÁË?y ?Ö»±»ÇóÖµÒ»´Î(µ«ÔÚÁ½ÖÖд·¨Ïµ±?x?<?y ?ֵΪ¼Ùʱ?z ?¶¼²»»á±»ÇóÖµ)¡£
ÕýʽµÄ˵·¨ÊÇÕâÑù:Èç¹û?a,?b,?c, ...,?y,?z?Ϊ±í´ïʽ¶ø?op1,?op2, ...,?opN?Ϊ±È½ÏÔËËã·û,Ôò?a?op1?b?op2?c?...?y?opN?z ?¾ÍµÈ¼ÛÓÚ?a?op1?b?and?b?op2?c?and?...?y?opN?z ,²»Í¬µãÔÚÓÚÿ¸ö±í´ïʽ×î¶àÖ»±»ÇóÖµÒ»´Î¡£
Çë×¢Òâ?a?op1?b?op2?c ?²»Òâζ×ÅÔÚ?a?ºÍ?c?Ö®¼ä½øÐÐÈκαȽÏ,Òò´Ë,Èç?x?<?y?>?z ?ÕâÑùµÄд·¨ÊÇÍêÈ«ºÏ·¨µÄ(ËäȻҲÐí²»Ì«ºÃ¿´)¡£
6.10.1.?Öµ±È½Ï
ÔËËã·û?< ,?> ,?== ,?>= ,?<= ?ºÍ?!= ?½«±È½ÏÁ½¸ö¶ÔÏóµÄÖµ¡£ Á½¸ö¶ÔÏó²»ÒªÇóΪÏàͬÀàÐÍ¡£
¶ÔÏó¡¢ÖµÓëÀàÐÍ?Ò»ÕÂÒÑ˵Ã÷¶ÔÏó¶¼ÓÐÏàÓ¦µÄÖµ(»¹ÓÐÀàÐͺͱêʶºÅ)¡£ ¶ÔÏóÖµÔÚ Python ÖÐÊÇÒ»¸öÏ൱³éÏóµÄ¸ÅÄî:ÀýÈç,¶ÔÏóÖµ²¢Ã»ÓÐÒ»¸ö¹æ·¶µÄ·ÃÎÊ·½·¨¡£ ¶øÇÒ,¶ÔÏóÖµ²¢²»ÒªÇó¾ßÓÐÌض¨µÄ¹¹½¨·½Ê½,ÀýÈçÓÉÆäÈ«²¿Êý¾ÝÊôÐÔ×é³ÉµÈ¡£ ±È½ÏÔËËã·ûʵÏÖÁËÒ»¸öÌض¨µÄ¶ÔÏóÖµ¸ÅÄî¡£ ÈËÃÇ¿ÉÒÔÈÏΪÕâÊÇͨ¹ýʵÏÖ¶ÔÏó±È½Ï¼ä½ÓµØ¶¨ÒåÁ˶ÔÏóÖµ¡£
ÓÉÓÚËùÓÐÀàÐͶ¼ÊÇ?object?µÄ(Ö±½Ó»ò¼ä½Ó)×ÓÀàÐÍ,ËüÃǶ¼´Ó?object?¼Ì³ÐÁËĬÈϵıȽÏÐÐΪ¡£ ÀàÐÍ¿ÉÒÔͨ¹ýʵÏÖ?·á¸»±È½Ï·½·¨?ÀýÈç?__lt__() ?À´¶¨Òå×Ô¼ºµÄ±È½ÏÐÐΪ,ÏêÇé²Î¼û?»ù±¾¶¨ÖÆ¡£
ĬÈϵÄÒ»ÖÂÐÔ±È½Ï (== ?ºÍ?!= ) ÊÇ»ùÓÚ¶ÔÏóµÄ±êʶºÅ¡£ Òò´Ë,¾ßÓÐÏàͬ±êʶºÅµÄʵÀýÒ»ÖÂÐԱȽϽá¹ûΪÏàµÈ,¾ßÓв»Í¬±êʶºÅµÄʵÀýÒ»ÖÂÐԱȽϽá¹ûΪ²»µÈ¡£ ¹æ¶¨ÕâÖÖĬÈÏÐÐΪµÄ¶¯»úÊÇÏ£ÍûËùÓжÔÏó¶¼Ó¦¸ÃÊÇ×Ô·´ÉäµÄ (¼´?x?is?y ?¾ÍÒâζ×Å?x?==?y )¡£
´ÎÐò±È½Ï (< ,?> ,?<= ?ºÍ?>= ) ĬÈÏûÓÐÌṩ;Èç¹û³¢ÊԱȽϻáÒý·¢?TypeError¡£ ¹æ¶¨ÕâÖÖĬÈÏÐÐΪµÄÔÒòÊÇȱÉÙÓëÒ»ÖÂÐԱȽÏÀàËƵĹ̶¨Öµ¡£
°´ÕÕĬÈϵÄÒ»ÖÂÐԱȽÏÐÐΪ,¾ßÓв»Í¬±êʶºÅµÄʵÀý×ÜÊDz»ÏàµÈ,Õâ¿ÉÄܲ»ÊʺÏijЩ¶ÔÏóÖµÐèÒªÓкÏÀí¶¨Òå²¢ÓлùÓÚÖµµÄÒ»ÖÂÐÔµÄÀàÐÍ¡£ ÕâÑùµÄÀàÐÍÐèÒª¶¨ÖÆ×Ô¼ºµÄ±È½ÏÐÐΪ,ʵ¼ÊÉÏ,Ðí¶àÄÚÖÃÀàÐͶ¼ÊÇÕâÑù×öµÄ¡£
ÒÔÏÂÁбíÃèÊöÁË×îÖ÷ÒªÄÚÖÃÀàÐ͵ıȽÏÐÐΪ¡£
-
ÄÚÖÃÊýÖµÀàÐÍ (Êý×ÖÀàÐÍ --- int, float, complex) ÒÔ¼°±ê×¼¿âÀàÐÍ?fractions.Fraction?ºÍ?decimal.Decimal?¿É½øÐÐÀàÐÍÄÚ²¿ºÍ¿çÀàÐ͵ıȽÏ,ÀýÍâÏÞÖÆÊǸ´Êý²»Ö§³Ö´ÎÐò±È½Ï¡£ ÔÚÀàÐÍÏà¹ØµÄÏÞÖÆÒÔÄÚ,ËüÃǻᰴÊýѧ(Ëã·¨)¹æÔòÕýÈ·½øÐбȽÏÇÒ²»»áÓÈËðʧ¡£ ·ÇÊý×ÖÖµ?float('NaN') ?ºÍ?decimal.Decimal('NaN') ?ÊôÓÚÌØÀý¡£ ÈκÎÊý×ÖÓë·ÇÊý×ÖÖµµÄÅÅÐò±È½Ï¾ù·µ»Ø¼ÙÖµ¡£ »¹ÓÐÒ»¸ö·´Ö±¾õµÄ½á¹ûÊÇ·ÇÊý×ÖÖµ²»µÈÓÚÆä×ÔÉí¡£ ¾ÙÀýÀ´Ëµ,Èç¹û?x?=?float('NaN') ?Ôò?3?<?x ,?x?<?3 ?ºÍ?x?==?x ?¾ùΪ¼ÙÖµ,¶ø?x?!=?x ?ÔòΪÕæÖµ¡£ ´ËÐÐΪÊÇ×ñÑ IEEE 754 ±ê×¼µÄ¡£ -
None ?ºÍ?NotImplemented ?¶¼Êǵ¥Àý¶ÔÏó¡£?PEP 8?½¨Òéµ¥Àý¶ÔÏóµÄ±È½ÏÓ¦µ±×ÜÊÇͨ¹ý?is ?»ò?is?not ?¶ø²»ÊǵÈÓÚÔËËã·ûÀ´½øÐС£ -
¶þ½øÖÆÂëÐòÁÐ (bytes?»ò?bytearray?µÄʵÀý) ¿É½øÐÐÀàÐÍÄÚ²¿ºÍ¿çÀàÐ͵ıȽϡ£ ËüÃÇʹÓÃÆäÔªËصÄÊý×ÖÖµ°´×Öµä˳Ðò½øÐбȽϡ£ -
×Ö·û´® (str?µÄʵÀý) ʹÓÃÆä×Ö·ûµÄ Unicode ÂëλÊý×ÖÖµ (ÄÚÖú¯Êý?ord()?µÄ½á¹û) °´×Öµä˳Ðò½øÐбȽϡ£?3 ×Ö·û´®ºÍ¶þ½øÖÆÂëÐòÁв»ÄÜÖ±½Ó±È½Ï¡£ -
ÐòÁÐ (tuple,?list?»ò?range?µÄʵÀý) Ö»¿É½øÐÐÀàÐÍÄÚ²¿µÄ±È½Ï,range »¹ÓÐÒ»¸öÏÞÖÆÊDz»Ö§³Ö´ÎÐò±È½Ï¡£ ÒÔÉ϶ÔÏóµÄ¿çÀàÐÍÒ»ÖÂÐԱȽϽá¹û½«ÊDz»ÏàµÈ,¿çÀàÐÍ´ÎÐò±È½Ï½«Òý·¢?TypeError¡£ ÐòÁбȽÏÊÇ°´×ÖµäÐò¶ÔÏàÓ¦ÔªËؽøÐÐÖð¸ö±È½Ï¡£ ÄÚÖÃÈÝÆ÷ͨ³£É趨ͬһ¶ÔÏóÓëÆä×ÔÉíÊÇÏàµÈµÄ¡£ ÕâʹµÃËüÃÇÄÜÌø¹ýͬһ¶ÔÏóµÄÏàµÈÐÔ¼ì²âÒÔÌáÉýÔËÐÐЧÂʲ¢±£³ÖËüÃǵÄÄÚ²¿²»±äÐÔ¡£ ÄÚÖöàÏ¼äµÄ×ÖµäÐò±È½Ï¹æÔòÈçÏÂ:
-
Á½¸ö¶àÏÈôÒªÏàµÈ,ËüÃDZØÐëΪÏàͬÀàÐÍ¡¢Ïàͬ³¤¶È,²¢ÇÒÿ¶ÔÏàÓ¦µÄÔªËض¼±ØÐëÏàµÈ(ÀýÈç,[1,2]?==?(1,2) ?Ϊ¼ÙÖµ,ÒòΪÀàÐͲ»Í¬)¡£ -
¶ÔÓÚÖ§³Ö´ÎÐò±È½ÏµÄ¶àÏ,ÅÅÐòÓëÆäµÚÒ»¸ö²»ÏàµÈÔªËصÄÅÅÐòÏàͬ(ÀýÈç?[1,2,x]?<=?[1,2,y] ?µÄÖµÓë``x <= y`` Ïàͬ)¡£ Èç¹û¶ÔÓ¦ÔªËز»´æÔÚ,½Ï¶ÌµÄ¶àÏÅÅÐòÔÚÇ°(ÀýÈç?[1,2]?<?[1,2,3] ?ΪÕæÖµ)¡£
-
Á½¸öÓ³Éä (dict?µÄʵÀý) ÈôÒªÏàµÈ,±ØÐëµ±ÇÒ½öµ±ËüÃǾßÓÐÏàͬµÄ?(¼ü, Öµ)?¶Ô¡£ ¼üºÍÖµµÄÒ»ÖÂÐԱȽÏÇ¿Öƹ涨×Ô·´ÉäÐÔ¡£ ´ÎÐò±È½Ï (< ,?> ,?<= ?ºÍ?>= ) ½«Òý·¢?TypeError¡£ -
¼¯ºÏ (set?»ò?frozenset?µÄʵÀý) ¿É½øÐÐÀàÐÍÄÚ²¿ºÍ¿çÀàÐ͵ıȽϡ£ ËüÃǽ«±È½ÏÔËËã·û¶¨ÒåΪ×Ó¼¯ºÍ³¬¼¯¼ì²â¡£ ÕâÀà¹ØϵûÓж¨ÒåÍêÈ«ÅÅÐò(ÀýÈç?{1,2} ?ºÍ?{2,3} ?Á½¸ö¼¯ºÏ²»ÏàµÈ,¼´²»Îª±Ë´ËµÄ×Ó¼¯,Ò²²»Îª±Ë´ËµÄ³¬¼¯¡£ ÏàÓ¦µØ,¼¯ºÏ²»ÊÊÒË×÷ΪÒÀÀµÓÚÍêÈ«ÅÅÐòµÄº¯ÊýµÄ²ÎÊý(ÀýÈçÈç¹û¸ø³öÒ»¸ö¼¯ºÏÁбí×÷Ϊ?min(),?max()?ºÍ?sorted()?µÄÊäÈ뽫²úÉú䶨ÒåµÄ½á¹û)¡£ ¼¯ºÏµÄ±È½ÏÇ¿Öƹ涨ÆäÔªËصÄ×Ô·´ÉäÐÔ¡£ -
´ó¶àÊýÆäËûÄÚÖÃÀàÐÍûÓÐʵÏֱȽϷ½·¨,Òò´ËËüÃÇ»á¼Ì³ÐĬÈϵıȽÏÐÐΪ¡£
ÔÚ¿ÉÄܵÄÇé¿öÏÂ,Óû§¶¨ÒåÀàÔÚ¶¨ÖÆÆä±È½ÏÐÐΪʱӦµ±×ñÑһЩһÖÂÐÔ¹æÔò:
-
ÏàµÈ±È½ÏÓ¦¸ÃÊÇ×Ô·´ÉäµÄ¡£ »»¾ä»°Ëµ,ÏàͬµÄ¶ÔÏó±È½ÏʱӦ¸ÃÏàµÈ:
x?is?y ?Òâζ×Å?x?==?y
-
±È½ÏÓ¦¸ÃÊǶԳƵġ£ »»¾ä»°Ëµ,ÏÂÁбí´ïʽӦ¸ÃÓÐÏàͬµÄ½á¹û:
x?==?y ?ºÍ?y?==?x
x?!=?y ?ºÍ?y?!=?x
x?<?y ?ºÍ?y?>?x
x?<=?y ?ºÍ?y?>=?x
-
±È½ÏÓ¦¸ÃÊÇ¿É´«µÝµÄ¡£ ÏÂÁÐ(¼òÒªµÄ)Àý×ÓÏÔʾÁËÕâÒ»µã:
x?>?y?and?y?>?z ?Òâζ×Å?x?>?z
x?<?y?and?y?<=?z ?Òâζ×Å?x?<?z
-
·´Ïò±È½ÏÓ¦¸Ãµ¼Ö²¼¶ûֵȡ·´¡£ »»¾ä»°Ëµ,ÏÂÁбí´ïʽӦ¸ÃÓÐÏàͬµÄ½á¹û:
x?==?y ?ºÍ?not?x?!=?y
x?<?y ?ºÍ?not?x?>=?y ?(¶ÔÓÚÍêÈ«ÅÅÐò)
x?>?y ?ºÍ?not?x?<=?y ?(¶ÔÓÚÍêÈ«ÅÅÐò)
×îºóÁ½¸ö±í´ïʽÊÊÓÃÓÚÍêÈ«ÅÅÐòµÄ¶àÏ(¼´ÐòÁжø·Ç¼¯ºÏ»òÓ³Éä)¡£ ÁíÇë²ÎÔÄ?total_ordering()?×°ÊÎÆ÷¡£ -
hash()?µÄ½á¹ûÓ¦¸ÃÓëÊÇ·ñÏàµÈÒ»Ö¡£ ÏàµÈµÄ¶ÔÏóÓ¦¸Ã»òÕß¾ßÓÐÏàͬµÄ¹þÏ£Öµ,»òÕß±ê¼ÇΪ²»¿É¹þÏ£¡£
Python ²¢²»Ç¿ÖÆÒªÇóÕâЩһÖÂÐÔ¹æÔò¡£ ʵ¼ÊÉÏ,·ÇÊý×ÖÖµ¾ÍÊÇÒ»¸ö²»×ñÑÕâЩ¹æÔòµÄÀý×Ó¡£
6.10.2.?³ÉÔ±¼ì²âÔËËã
ÔËËã·û?in?ºÍ?not?in?ÓÃÓÚ³ÉÔ±¼ì²â¡£ Èç¹û?x?ÊÇ?s?µÄ³ÉÔ±Ôò?x?in?s ?ÇóֵΪ?True ,·ñÔòΪ?False ¡£?x?not?in?s ?·µ»Ø?x?in?s ?È¡·´ºóµÄÖµ¡£ ËùÓÐÄÚÖÃÐòÁкͼ¯ºÏÀàÐÍÒÔ¼°×ֵ䶼֧³Ö´ËÔËËã,¶ÔÓÚ×ÖµäÀ´Ëµ?in ?¼ì²âÆäÊÇ·ñÓиø¶¨µÄ¼ü¡£ ¶ÔÓÚ list, tuple, set, frozenset, dict »ò collections.deque ÕâÑùµÄÈÝÆ÷ÀàÐÍ,±í´ïʽ?x?in?y ?µÈ¼ÛÓÚ?any(x?is?e?or?x?==?e?for?e?in?y) ¡£
¶ÔÓÚ×Ö·û´®ºÍ×Ö½Ú´®ÀàÐÍÀ´Ëµ,µ±ÇÒ½öµ±?x?ÊÇ?y?µÄ×Ó´®Ê±?x?in?y ?Ϊ?True ¡£ Ò»¸öµÈ¼ÛµÄ¼ì²âÊÇ?y.find(x)?!=?-1 ¡£ ¿Õ×Ö·û´®×ÜÊDZ»ÊÓΪÈκÎÆäËû×Ö·û´®µÄ×Ó´®,Òò´Ë?""?in?"abc" ?½«·µ»Ø?True ¡£
¶ÔÓÚ¶¨ÒåÁË?__contains__() ?·½·¨µÄÓû§×Ô¶¨ÒåÀàÀ´Ëµ,Èç¹û?y.__contains__(x) ?·µ»ØÕæÖµÔò?x?in?y ?·µ»Ø?True ,·ñÔò·µ»Ø?False ¡£
¶ÔÓÚ䶨Òå?__contains__() ?µ«¶¨ÒåÁË?__iter__() ?µÄÓû§×Ô¶¨ÒåÀàÀ´Ëµ,Èç¹ûÔÚ¶Ô?y ?½øÐеü´úʱ²úÉúÁËÖµ?z ?ʹµÃ±í´ïʽ?x?is?z?or?x?==?z ?ΪÕæ,Ôò?x?in?y ?Ϊ?True ¡£ Èç¹ûÔÚµü´úÆÚ¼äÒý·¢ÁËÒì³£,ÔòµÈͬÓÚ?in?Òý·¢Á˸ÃÒì³£¡£
×îºó½«»á³¢ÊÔ¾ÉʽµÄµü´úÐÒé:Èç¹ûÒ»¸öÀඨÒåÁË?__getitem__() ,Ôòµ±ÇÒ½öµ±´æÔڷǸºÕûÊýË÷ÒýºÅ?i?ʹµÃ?x?is?y[i]?or?x?==?y[i] ?²¢ÇÒûÓиüСµÄË÷ÒýºÅÒý·¢?IndexError?Ò쳣ʱ?x?in?y ?Ϊ?True ¡£ (Èç¹ûÒý·¢ÁËÈκÎÆäËûÒì³£,ÔòµÈͬÓÚ?in?Òý·¢Á˸ÃÒì³£)¡£
ÔËËã·û?not?in?±»¶¨ÒåΪ¾ßÓÐÓë?in?Ïà·´µÄÂß¼Öµ¡£
6.10.3.?±êʶºÅ±È½Ï
ÔËËã·û?is?ºÍ?is?not?ÓÃÓÚ¼ì²â¶ÔÏóµÄ±êʶºÅ:µ±ÇÒ½öµ±?x?ºÍ?y?ÊÇͬһ¶ÔÏóʱ?x?is?y ?ΪÕæ¡£ Ò»¸ö¶ÔÏóµÄ±êʶºÅ¿ÉʹÓÃ?id()?º¯ÊýÀ´È·¶¨¡£?x?is?not?y ?»á²úÉúÏà·´µÄÂß¼Öµ¡£?4
6.11.?²¼¶ûÔËËã
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
ÔÚÖ´Ðв¼¶ûÔËËãµÄÇé¿öÏÂ,»òÊǵ±±í´ïʽ±»ÓÃÓÚÁ÷³Ì¿ØÖÆÓï¾äʱ,ÒÔÏÂÖµ»á±»½âÎöΪ¼ÙÖµ:?False ,?None , ËùÓÐÀàÐ͵ÄÊý×ÖÁã,ÒÔ¼°¿Õ×Ö·û´®ºÍ¿ÕÈÝÆ÷(°üÀ¨×Ö·û´®¡¢Ôª×é¡¢ÁÐ±í¡¢×ֵ䡢¼¯ºÏÓ붳½á¼¯ºÏ)¡£ ËùÓÐÆäËûÖµ¶¼»á±»½âÎöΪÕæÖµ¡£ Óû§×Ô¶¨Òå¶ÔÏó¿Éͨ¹ýÌṩ?__bool__() ?·½·¨À´¶¨ÖÆÆäÂß¼Öµ¡£
ÔËËã·û?not?½«ÔÚÆä²ÎÊýΪ¼Ùֵʱ²úÉú?True ,·ñÔò²úÉú?False ¡£
±í´ïʽ?x?and?y ?Ê×ÏȶÔ?x?ÇóÖµ;Èç¹û?x?Ϊ¼ÙÔò·µ»Ø¸ÃÖµ;·ñÔò¶Ô?y?ÇóÖµ²¢·µ»ØÆä½á¹ûÖµ¡£
±í´ïʽ?x?or?y ?Ê×ÏȶÔ?x?ÇóÖµ;Èç¹û?x?ΪÕæÔò·µ»Ø¸ÃÖµ;·ñÔò¶Ô?y?ÇóÖµ²¢·µ»ØÆä½á¹ûÖµ¡£
Çë×¢Òâ?and?ºÍ?or?¶¼²»ÏÞÖÆÆä·µ»ØµÄÖµºÍÀàÐͱØÐëΪ?False ?ºÍ?True ,¶øÊÇ·µ»Ø×îºó±»ÇóÖµµÄ²Ù×÷Êý¡£ ´ËÐÐΪÊÇÓбØÒªµÄ,ÀýÈç¼ÙÉè?s ?Ϊһ¸öµ±ÆäΪ¿ÕʱӦ±»Ì滻Ϊij¸öĬÈÏÖµµÄ×Ö·û´®,±í´ïʽ?s?or?'foo' ?½«²úÉúÏ£ÍûµÄÖµ¡£ ÓÉÓÚ?not?±ØÐë´´½¨Ò»¸öÐÂÖµ,²»ÂÛÆä²ÎÊýΪºÎÖÖÀàÐÍËü¶¼»á·µ»ØÒ»¸ö²¼¶ûÖµ(ÀýÈç,not?'foo' ?½á¹ûΪ?False ?¶ø·Ç?'' ¡£)
6.12.?¸³Öµ±í´ïʽ
assignment_expression ::= [identifier ":="] expression
An assignment expression (sometimes also called a "named expression" or "walrus") assigns an?expression?to an?identifier, while also returning the value of the?expression.
Ò»¸ö³£¼ûÓÃÀýÊÇÔÚ´¦ÀíÆ¥ÅäµÄÕýÔò±í´ïʽµÄʱºò:
if matching := pattern.search(data):
do_something(matching)
»òÕßÊÇÔÚ´¦Àí·Ö¿éµÄÎļþÁ÷µÄʱºò:
while chunk := file.read(9000):
process(chunk)
3.8 а湦ÄÜ:?Çë²ÎÔÄ?PEP 572?Á˽âÓйظ³Öµ±í´ïʽµÄÏêÇé¡£
6.13.?Ìõ¼þ±í´ïʽ
conditional_expression ::= or_test ["if" or_test "else" expression]
expression ::= conditional_expression | lambda_expr
Ìõ¼þ±í´ïʽ(ÓÐʱ³ÆΪ¡°ÈýÔªÔËËã·û¡±)ÔÚËùÓÐ Python ÔËËãÖоßÓÐ×îµÍµÄÓÅÏȼ¶¡£
±í´ïʽ?x?if?C?else?y ?Ê×ÏÈÊǶÔÌõ¼þ?C?¶ø·Ç?x?ÇóÖµ¡£ Èç¹û?C?ΪÕæ,x?½«±»ÇóÖµ²¢·µ»ØÆäÖµ;·ñÔò½«¶Ô?y?ÇóÖµ²¢·µ»ØÆäÖµ¡£
Çë²ÎÔÄ?PEP 308?Á˽âÓйØÌõ¼þ±í´ïʽµÄÏêÇé¡£
6.14.?lambda ±í´ïʽ
lambda_expr ::= "lambda" [parameter_list] ":" expression
lambda ±í´ïʽ(ÓÐʱ³ÆΪ lambda ¹¹ÐÍ)±»ÓÃÓÚ´´½¨ÄäÃûº¯Êý¡£ ±í´ïʽ?lambda?parameters:?expression ?»á²úÉúÒ»¸öº¯Êý¶ÔÏó ¡£ ¸ÃδÃüÃû¶ÔÏóµÄÐÐΪÀàËÆÓÚÓÃÒÔÏ·½Ê½¶¨ÒåµÄº¯Êý:
def <lambda>(parameters):
return expression
Çë²ÎÔÄ?º¯Êý¶¨Òå?Á˽âÓйزÎÊýÁбíµÄ¾ä·¨¡£ Çë×¢Òâͨ¹ý lambda ±í´ïʽ´´½¨µÄº¯Êý²»ÄÜ°üº¬Óï¾ä»ò±ê×¢¡£
6.15.?±í´ïʽÁбí
expression_list ::= expression ("," expression)* [","]
starred_list ::= starred_item ("," starred_item)* [","]
starred_expression ::= expression | (starred_item ",")* [starred_item]
starred_item ::= assignment_expression | "*" or_expr
³ýÁË×÷ΪÁбí»ò¼¯ºÏÏÔʾµÄÒ»²¿·Ö,°üº¬ÖÁÉÙÒ»¸ö¶ººÅµÄ±í´ïʽÁÐ±í½«Éú³ÉÒ»¸öÔª×é¡£ Ôª×éµÄ³¤¶È¾ÍÊÇÁбíÖбí´ïʽµÄÊýÁ¿¡£ ±í´ïʽ½«´Ó×óÖÁÓÒ±»ÇóÖµ¡£
Ò»¸öÐǺÅ?* ?±íʾ?¿Éµü´ú²ð°ü¡£ Æä²Ù×÷Êý±ØÐëΪһ¸ö?iterable¡£ ¸Ã¿Éµü´ú¶ÔÏ󽫱»²ð½âΪµü´úÏîµÄÐòÁÐ,²¢±»°üº¬ÓÚÔÚ²ð°üλÖÃÉÏн¨µÄÔª×é¡¢Áбí»ò¼¯ºÏÖ®ÖС£
3.5 а湦ÄÜ:?±í´ïʽÁбíÖеĿɵü´ú¶ÔÏó²ð°ü,×î³õÓÉ?PEP 448?Ìá³ö¡£
ĩβµÄ¶ººÅ½öÔÚ´´½¨µ¥¶ÀÔª×é (»ò³Æ?µ¥Àý) ʱÐèÒª;ÔÚËùÓÐÆäËûÇé¿ö϶¼ÊÇ¿ÉÑ¡Ïî¡£ ûÓÐĩβ¶ººÅµÄµ¥¶À±í´ïʽ²»»á´´½¨Ò»¸öÔª×é,¶øÊDzúÉú¸Ã±í´ïʽµÄÖµ¡£ (Òª´´½¨Ò»¸ö¿ÕÔª×é,ӦʹÓÃÒ»¶ÔÄÚÈÝΪ¿ÕµÄÔ²À¨ºÅ:?() ¡£)
6.16.?Çóֵ˳Ðò
Python °´´Ó×óÖÁÓÒµÄ˳Ðò¶Ô±í´ïʽÇóÖµ¡£ µ«×¢ÒâÔÚ¶Ô¸³Öµ²Ù×÷Çóֵʱ,ÓÒ²à»áÏÈÓÚ×ó²à±»ÇóÖµ¡£
ÔÚÒÔϼ¸ÐÐÖÐ,±í´ïʽ½«°´Æäºó׺µÄËãÊõÓÅÏÈ˳Ðò±»ÇóÖµ¡£:
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2
6.17.?ÔËËã·ûÓÅÏȼ¶
ϱí¶Ô Python ÖÐÔËËã·ûµÄÓÅÏÈ˳Ðò½øÐÐÁË×ܽá,´Ó×î¸ßÓÅÏȼ¶(×îÏÈ°ó¶¨)µ½×îµÍÓÅÏȼ¶(×îºó°ó¶¨)¡£ Ïàͬµ¥Ôª¸ñÄÚµÄÔËËã·û¾ßÓÐÏàͬÓÅÏȼ¶¡£ ³ý·Ç¾ä·¨ÏÔʽµØ¸ø³ö,·ñÔòÔËËã·û¾ùÖ¸¶þÔªÔËËã¡£ Ïàͬµ¥Ôª¸ñÄÚµÄÔËËã·û´Ó×óÖÁÓÒ·Ö×é(³ýÁËÃÝÔËËãÊÇ´ÓÓÒÖÁ×ó·Ö×é)¡£
Çë×¢Òâ±È½Ï¡¢³ÉÔ±¼ì²âºÍ±êʶºÅ¼ì²â¾ùΪÏàͬÓÅÏȼ¶,²¢¾ßÓÐÈç?±È½ÏÔËËã?Ò»½ÚËùÃèÊöµÄ´Ó×óÖÁÓÒ´®Á¬ÌØÐÔ¡£
ÔËËã·û | ÃèÊö |
---|
(expressions...) , [expressions...] ,?{key:?value...} ,?{expressions...} | °ó¶¨»ò¼ÓÔ²À¨ºÅµÄ±í´ïʽ,ÁбíÏÔʾ,×ÖµäÏÔʾ,¼¯ºÏÏÔʾ | x[index] ,?x[index:index] ,?x(arguments...) ,?x.attribute | ³éÈ¡,ÇÐƬ,µ÷ÓÃ,ÊôÐÔÒýÓà | await?x | await ±í´ïʽ | ** | ³Ë·½?5 | +x ,?-x ,?~x | Õý,¸º,°´Î»·Ç NOT | * ,?@ ,?/ ,?// ,?% | ³Ë,¾ØÕó³Ë,³ý,Õû³ý,È¡Óà?6 | + ,?- | ¼ÓºÍ¼õ | << ,?>> | ÒÆλ | & | °´Î»Óë AND | ^ | °´Î»Òì»ò XOR | | | °´Î»»ò OR | in,?not?in,?is,?is?not,?< ,?<= ,?> ,?>= ,?!= ,?== | ±È½ÏÔËËã,°üÀ¨³ÉÔ±¼ì²âºÍ±êʶºÅ¼ì²â | not?x | ²¼¶ûÂß¼·Ç NOT | and | ²¼¶ûÂß¼Óë AND | or | ²¼¶ûÂß¼»ò OR | if?--?else | Ìõ¼þ±í´ïʽ | lambda | lambda ±í´ïʽ | := | ¸³Öµ±í´ïʽ |
±¸×¢
1
ËäÈ»?abs(x%y)?<?abs(y) ?ÔÚÊýѧÖбØΪÕæ,µ«¶ÔÓÚ¸¡µãÊý¶øÑÔ,ÓÉÓÚÉáÈëµÄ´æÔÚ,ÆäÔÚÊýÖµÉÏδ±ØΪÕæ¡£ ÀýÈç,¼ÙÉèÔÚij¸öƽ̨É쵀 Python ¸¡µãÊýΪһ¸ö IEEE 754 Ë«¾«¶ÈÊýÖµ,ΪÁËʹ?-1e-100?%?1e100 ?¾ßÓÐÓë?1e100 ?ÏàͬµÄÕý¸ºÐÔ,¼ÆËã½á¹û½«ÊÇ?-1e-100?+?1e100 ,ÕâÔÚÊýÖµÉÏÕýºÃµÈÓÚ?1e100 ¡£ º¯Êý?math.fmod()?·µ»ØµÄ½á¹ûÔò»á¾ßÓÐÓëµÚÒ»¸ö²ÎÊýÏàͬµÄÕý¸ºÐÔ,Òò´ËÔÚÕâÖÖÇé¿öϽ«·µ»Ø?-1e-100 ¡£ ºÎÖÖ·½Ê½¸üÊÊÒËÈ¡¾öÓÚ¾ßÌåµÄÓ¦Óá£
2
Èç¹û x Ç¡ºÃ·Ç³£½Ó½üÓÚ y µÄÕûÊý±¶,ÔòÓÉÓÚÉáÈëµÄ´æÔÚ?x//y ?¿ÉÄÜ»á±È?(x-x%y)//y ?´ó¡£ ÔÚÕâÖÖÇé¿öÏÂ,Python »á·µ»ØºóÒ»¸ö½á¹û,ÒԱ㱣³ÖÁî?divmod(x,y)[0]?*?y?+?x?%?y ?¾¡Á¿½Ó½ü?x .
3
Unicode ±ê×¼Ã÷È·Çø·Ö?Âëλ?(ÀýÈç U+0041) ºÍ?³éÏó×Ö·û?(ÀýÈç "´óдÀ¶¡×Öĸ A")¡£ ËäÈ» Unicode ÖеĴó¶àÊý³éÏó×Ö·û¶¼Ö»ÓÃÒ»¸öÂëλÀ´´ú±í,µ«Ò²´æÔÚһЩ³éÏó×Ö·û¿ÉʹÓÃÓɶà¸öÂëλ×é³ÉµÄÐòÁÐÀ´±íʾ¡£ ÀýÈç,³éÏó×Ö·û "´øÓÐϼӷûµÄ´óдÀ¶¡×Öĸ C" ¿ÉÒÔÓà U+00C7 ÂëλÉϵĵ¥¸ö?Ô¤Éè×Ö·û?À´±íʾ,Ò²¿ÉÒÔÓÃÒ»¸ö U+0043 ÂëλÉϵÄ?»ù´¡×Ö·û?(´óдÀ¶¡×Öĸ C) ¼ÓÉÏÒ»¸ö U+0327 ÂëλÉϵÄ?×éºÏ×Ö·û?(×éºÏϼӷû) ×é³ÉµÄÐòÁÐÀ´±íʾ¡£
¶ÔÓÚ×Ö·û´®,±È½ÏÔËËã·û»á°´ Unicode Âëλ¼¶±ð½øÐбȽϡ£ Õâ¿ÉÄÜ»áÎ¥·´ÈËÀàµÄÖ±¾õ¡£ ÀýÈç,"\u00C7"?==?"\u0043\u0327" ?Ϊ?False ,ËäÈ»Á½¸ö×Ö·û´®¶¼´ú±íͬһ¸ö³éÏó×Ö·û "´øÓÐϼӷûµÄ´óдÀ¶¡×Öĸ C"¡£
Òª°´³éÏó×Ö·û¼¶±ð(¼´¶ÔÈËÀàÀ´Ëµ¸üÖ±¹ÛµÄ·½Ê½)¶Ô×Ö·û´®½øÐбȽÏ,ӦʹÓÃ?unicodedata.normalize()¡£
4
ÓÉÓÚ´æÔÚ×Ô¶¯À¬»øÊÕ¼¯¡¢¿ÕÏÐÁбíÒÔ¼°ÃèÊöÆ÷µÄ¶¯Ì¬ÌØÐÔ,Äã¿ÉÄÜ»á×¢Òâµ½ÔÚÌض¨Çé¿öÏÂʹÓÃ?is?ÔËËã·û»á³öÏÖ¿´ËƲ»Õý³£µÄÐÐΪ,ÀýÈçÉæ¼°µ½ÊµÀý·½·¨»ò³£Á¿Ö®¼äµÄ±È½Ïʱ¾ÍÊÇÈç´Ë¡£ ¸ü¶àÐÅÏ¢Çë²é¿´ÓйØËüÃǵÄÎĵµ¡£
5
ÃÝÔËËã·û?** ?°ó¶¨µÄ½ôÃ̶ܳȵÍÓÚÔÚÆäÓÒ²àµÄËãÊõ»ò°´Î»Ò»ÔªÔËËã·û,Ò²¾ÍÊÇ˵?2**-1 ?Ϊ?0.5 ¡£
6
% ?ÔËËã·ûÒ²±»ÓÃÓÚ×Ö·û´®¸ñʽ»¯;Ôڴ˳¡ºÏÏ»áʹÓÃͬÑùµÄÓÅÏȼ¶¡£
?
|