Python3.12即将发布RC版,有哪些新特性?

2023-06-1320:25:51编程语言入门到精通Comments1,968 views字数 1446阅读模式

6月11,Python发布了3.12的bate版本3.12.0b2,预计在7月31日发布RC版。语法层面上新增了一些特性,整体的性能也得到了一定的提升,这里介绍几个使用的语法特性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

1、提供了错误消息的可读性

在3.11及以前版本,如果模块没有导入时的错误提示时,只告诉你报错原因文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

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

现在,它还会告诉你修改建议文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

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

比如代码中提示sys没有被定义,会问题是不是忘记import了。其实这种错误,先进一点的IDE都会自动帮你导入了。但对新手来说还是比较友好的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

2、增强的f-string

f-string早在3.6就引入的一种字符出格式化方法,也被称为格式化字符串常量,相比老式的格式化方法简洁很多。现在3.12版本中又增强了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

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

这段代码在3.11会提示语法错误,在字符串中不允许相同的引号同时存在字符串中,如果外层是双引号,里面必须是用单引号,例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

print(f"This is the playlist: {', '.join(songs)}")

现在就不存在这个问题了,你甚至可以多个引号对同时存在,例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

f"{f"{f"{f"{f"{f"{1+1}"}"}"}"}"}"

不过从可读性角度来说,这么多引号放一起看起来有点晕。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

3、新增override装饰器

@override在Java中出现过,这个装饰器的用途是当子类的方法想覆盖父类方法的默认实现时,可通过这个装饰器来表示,用来告诉编译器,这是一个被重写的方法,当字类的该方法被调用时,不要再去调父类的方法了,现在Python也可以这么用了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

from typing import override

class 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"

注意,override 修饰错了方法也不会导致程序报错,Python动态语言特性的缘故,静态类型检查只是一种建设性的提示,只有在做类型检查的时候才会提示错误。类型检查这块,Python其实都是从静态语言中参考过来的,代码中加入类型检查,“重构火葬场”的场面基本可以宣告终止了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

完整特性请参考:https://docs.python.org/dev/whatsnew/3.12.html文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/46947.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/46947.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定