龙空技术网

Python3.12新特性,不止更新了个“寂寞”

博学多才的叶慢慢 3301

前言:

现时各位老铁们对“python3语句”大概比较看重,大家都需要剖析一些“python3语句”的相关内容。那么小编也在网上网罗了一些有关“python3语句””的相关内容,希望我们能喜欢,兄弟们快快来了解一下吧!

作者: 麦叔编程

来源: 麦叔编程

Python3每次更新版本,都会有小道消息说会取消GIL(全局解释锁),但实际...

Python3.12带来的新特性改进报错提醒

Python3.12之前模块忘记导入是这样的:

>>> sys.version_infoTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'sys' is not defined

新版本会提醒你是否忘记导入模块:

>>> sys.version_infoTraceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'sys' is not defined. Did you forget to import 'sys'?

忘记在类中写self也会提醒你:

class A:   def __init__(self):       self.blech = 1   def foo(self):       somethin = blech
>>> A().foo()Traceback (most recent call last):  File "<stdin>", line 1    somethin = blech               ^^^^^NameError: name 'blech' is not defined. Did you mean: 'self.blech'?

from...import...语句写反也会提醒你:

import a.y.z from b.y.zTraceback (most recent call last):  File "<stdin>", line 1    import a.y.z from b.y.z    ^^^^^^^^^^^^^^^^^^^^^^^SyntaxError: Did you mean to use 'from ... import ...' instead?

导入模块时,稍稍写错了模块名也会提醒你:

from collections import chainmapTraceback (most recent call last):  File "<stdin>", line 1, in <module>ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?
强化f-string语句功能

f"{}"中可以使用表达式了~

>>> songs = ['Take me back to Eden', 'Alkaline', 'Ascensionism']>>> f"This is the playlist: {", ".join(songs)}"'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'

f"{}"可以嵌套了~

f"""{f'''{f'{f"{1+1}"}'}'''}"""'2'

多行表达式和注释:

>>> f"This is the playlist: {", ".join([...     'Take me back to Eden',  # My, my, those eyes like fire...     'Alkaline',              # Not acid nor alkaline...     'Ascensionism'           # Take to the broken skies at last... ])}"'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'

反斜杠和unicode字符!!

这个真的很赞!以前要是f-string表达式中出现\字符,这个表达式基本就废了,现在靠反斜杠转下就行了!

print(f"This is the playlist: {"\n".join(songs)}")This is the playlist: Take me back to EdenAlkalineAscensionismprint(f"This is the playlist: {"\N{BLACK HEART SUIT}".join(songs)}")This is the playlist: Take me back to Eden♥Alkaline♥Ascensionism
override装饰器

@override在Java中经常被使用,它的用途是当子类的方法想覆盖父类方法的默认实现时。

通过@override装饰器来表示,用来告诉编译器,这是一个被重写的方法,当重写的子方法被调用时,不需再去调父类的方法了。

from typing import overrideclass Base:  def get_color(self) -> str:    return "blue"class GoodChild(Base):  @override  # ok: overrides Base.get_color  def get_color(self) -> str:    return "yellow"class BadChild(Base):  @override  # type checker error: does not override Base.get_color  def get_colour(self) -> str:    return "red"

Python一直向Java靠拢,Java一直向Python学习。

最后

据说Python3.12还更新了子解释器这个概念Sub-Interpreters,这难道离突破GIL的封锁又近了一步?

有兴趣的小伙伴可以通过以下传送门学习研究下Sub-Interpreters的使用,本文就不赘述了。

>>> 传送门:Real Multithreading is Coming to Python - Learn How You Can Use It Now <<<

标签: #python3语句