python隐藏标题_python的隐藏类

python隐藏标题

In this article we’ll explore two powerful features of python present in the standard library yet almost always missed through their lack of publicity.

在本文中,我们将探讨标准库中存在的python的两个强大功能,但由于缺乏宣传而几乎总是被忽略。

资料类别 (Dataclasses)

Recently I’ve had the privilege of getting code reviews. In the process of other programmers inspecting my code for faults, blemishes and other programming gremlins more than one person (two actually) have asked what this is all about:

最近,我荣幸地获得了代码审查。 在其他程序员检查我的代码中是否有错误,瑕疵和其他编程怪物的过程中,一个以上的人(实际上是两个)问这是怎么回事:

@dataclass
class Car:
doors: int

In the context of Python 3.7+ ‘this’ is a dataclass, a powerful and interesting feature that few people come across. Despite appearances it’s also valid code which is always an advantage¹. Dataclasses were introduced in Python as a means to make code as fast as python allows, while at the same time making it appear professional with less duplication. It achieves this with nothing more than the definition of the data to store. And defining our data is made easy, we just list the variables in a dataclass indent. Absolutely everything else is done for us in an internal optimized fashion, most notably including the creation of the __init__ constructor method, the assignment of all its variables and a bunch of other stuff. A complete example is as simple as this:

在Python 3.7+中,“这”是一个数据类,这是一个功能强大且有趣的功能,很少有人遇到。 尽管有外观,但它也是有效的代码,始终是一个优势¹。 数据类是在Python中引入的,它是使代码在python允许的范围内快速运行的一种方法,同时又使它看起来很专业,并且减少了重复。 它仅需定义要存储的数据即可实现此目的。 定义数据变得容易,我们只需在数据类缩进中列出变量即可。 绝对所有其他事情都以内部优化的方式为我们完成,最著名的是包括__init__构造函数方法的创建,其所有变量的分配以及许多其他工作。 一个完整的例子很简单:

from dataclasses import dataclass@dataclass 
class Car:
doors: int
windows: int
paint_work: str

With only a few lines of code we create and initialise instances, assign values and have accessor methods created all for free. We can create each new instance object with either named parameters or positional parameters and Python will both understand what we pass and assign values to the correct variable.

我们仅用几行代码就可以创建和初始化实例,分配值并免费创建所有访问器方法。 我们可以使用命名参数或位置参数创建每个新的实例对象,Python都将理解我们传递的内容并将值分配给正确的变量。

mustang = C
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值