iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >13 个 python3 才能用的特性
  • 908
分享到

13 个 python3 才能用的特性

能用特性 2023-01-31 02:01:02 908人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

分享来源13 个 python3 才能用的特性 python3 于 2008 年发布,从最初的大割裂到现在,绝大多数的开源库已经使用 Python3 来编写,并且已经迭代了五个大版本,最新的 python3.7 计划于 2018 年 6

分享来源13 个 python3 才能用的特性

python3 于 2008 年发布,从最初的大割裂到现在,绝大多数的开源库已经使用 Python3 来编写,并且已经迭代了五个大版本,最新的 python3.7 计划于 2018 年 6 月 15 发布正式版。而 python2.7 作为 python2 的最后一个版本,将于 2020 年 1 月停止维护。

更多Python视频、源码、资料加群683380553免费获取

python3 的使用率在很久的一段时间里增长非常缓慢,是的,大多数人只觉得 python3 只是改了输出语句 print(),而并没有意识到实际上 python3 所具有的大量新特性。虽然说可以用 import __future__ 来在 python2 使用部分特性,但是以下 13 点非常好用的特性是你在 python2 中完全无法体验到的。

 

我们从 https://www.asmeurer.com/python3-presentation/slides.html 中整理并翻译了 python3 的特性,剔除了部分老旧的代码,整理了相关例子,并提供了 jupyter notebook 版本以及 html 版,获取方法在本文末。

 

特性 1: 高级解包

交换两个变量的值在 python 中非常简单,你也许已经在 python2 中大量使用以下方法:


a, b = 1, 2
a, b = b, a
print(a, b)
##> 2, 1

 

使用解包交换变量非常方便,在 python3 中,这个特性得到了加强,现在你可以这样做:


a, b, *rest = range(10)
print('a:', a)
print('b:', b)
print('rest:', rest)
##> a: 0
##> b: 1
##> rest: [2, 3, 4, 5, 6, 7, 8, 9]

 

rest 可以在任何位置,比如这样:


a, *rest, b = range(10)
print('rest', rest)
##> rest [1, 2, 3, 4, 5, 6, 7, 8]

*rest, b = range(10)
print('rest', rest)
##> rest [0, 1, 2, 3, 4, 5, 6, 7, 8]

 

使用 python 获得文件的第一行和最后一行内容。


with open('use_python_to_profit.txt') as f:
    first, *_, last = f.readlines() # 注意,这会读取所有内容到内存中

print('first:', first)
print('last:', last)
##> first: step 1: use python
##> last: step 10: profit

 

特性 2: 强制关键词参数


def f(a, b, *args, option=True):
    pass

 

如果你用以上写法来写一个函数,那么你限定了调用参数时,必须要这样写 f(a, b, option=True)

如果你不想收集其他参数,你可以用 * 代替 *args,比如这样:


def f(a, b, *, option=True):
    pass

 

当你碰上这种事情:哎呀,我不小心传递太多参数给函数,其中之一会被关键字参数接收,然后程序原地爆炸了。


def sum(a, b, biteme=False):
    if biteme:
        print('一键删库')
    else:
        return a + b

sum(1, 2)
##> 3
sum(1, 2, 3)
##> 一键删库.

.. .所以,以后千万别这样写,为了你的下半生能够过上平静的日子,你应该这样:


def sum(a, b, *, biteme=False):
    if biteme:
        print('一键删库')
    else:
        return a + b

 

试一下不合法的调用:


sum(1, 2, 3)
##> TypeError: sum() takes 2 positional arguments but 3 were given

 

有时你会想写这样一个方法


def maxall(iterable, key=None):
    """
    返回一个列表中的最大值
    """
    key = key or (lambda x: x)
    m = max(iterable, key=key)
    return [i for i in iterable if key(i) == key(m)]

maxall(['a', 'ab', 'bc'], len)
##> ['ab', 'bc']

 

但是你又想像内置的max()函数那样允许 max(a, b, c) 的写法,但是这两种传参方法似乎不能和平相处:


def maxall(*args, key=None):
   """
   A list of all max items from the iterable
   """
   if len(args) == 1:
       iterable = args[0]
   else:
       iterable = args
   key = key or (lambda x: x)
   m = max(iterable, key=key)
   return [i for i in iterable if key(i) == key(m)]

maxall(['a', 'bc', 'cd'], len)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-e8f4c154d310> in <module>()
     11     return [i for i in iterable if key(i) == key(m)]
     12 
---> 13 maxall(['a', 'bc', 'cd'], len)

<ipython-input-22-e8f4c154d310> in maxall(key, *args)
      8         iterable = args
      9     key = key or (lambda x: x)
---> 10     m = max(iterable, key=key)
     11     return [i for i in iterable if key(i) == key(m)]
     12 

TypeError: unorderable types: builtin_function_or_method() > list()

 

显然,我们应该用max(iterable, *, key=None)来写这个函数。你在写代码时,也可以用关键词参数使你的 api 具有更好的扩展性。


# 蠢蠢的写法
def extendto(value, shorter, longer):
    """
    使短的 list 填充到和长的 list 一样长,填充为 value
    """
    if len(shorter) > len(longer):
        raise ValueError('The `shorter` list is longer than the `longer` list')
    shorter.extend([value]*(len(longer) - len(shorter)))

a = [1, 2]
b = [1, 2, 3, 4, 5]

extendto(10, a, b)

print('a', a)
##> a [1, 2, 10, 10, 10]

 

当你碰上这种事情:哎呀,我不小心传递太多参数给函数,其中之一会被关键字参数接收,然后程序原地爆炸了。


# 更好的写法
def extendto(value, *, shorter=None, longer=None):
    """
    Extend list `shorter` to the length of list `longer` with `value`
    """
    if shorter is None or longer is None:
        raise TypeError('`shorter` and `longer` must be specified')
    if len(shorter) > len(longer):
        raise ValueError('The `shorter` list is longer than the `longer` list')
    shorter.extend([value]*(len(longer) - len(shorter)))

 

我们可以用 extendto(10, shorter=a, longer=b) 的方式调用这个方法,以后我们要修改这个接口的传参方式时,也不用修改已有代码啦。

 

特性 3:链式异常

现在你在写一个函数,由于可能会出现错误,你打算 catch 可能出现的异常,做一些额外的工作,然后再抛出另一种异常。


import shutil

def mycopy(source, dest):
    try:
        shutil.copy2(source, dest)
    except OSError: # We don't have permissions. More on this later
        raise NotImplementedError("automatic sudo injection")

 

如果你用 python2 的话得到的是,你把第一个异常信息丢了,只能一脸懵逼。


>>> mycopy(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in mycopy
NotImplementedError: automatic sudo injection

 

python3 中会依次把异常记录下来


mycopy(1, 2)

---------------------------------------------------------------------------
SameFileError                             Traceback (most recent call last)
<ipython-input-26-7970d14296a0> in mycopy(source, dest)
      4     try:
----> 5         shutil.copy2(source, dest)
      6     except OSError: # We don't have permissions. More on this later

/usr/lib/python3.5/shutil.py in copy2(src, dst, follow_symlinks)
    250         dst = os.path.join(dst, os.path.basename(src))
--> 251     copyfile(src, dst, follow_symlinks=follow_symlinks)
    252     copystat(src, dst, follow_symlinks=follow_symlinks)

/usr/lib/python3.5/shutil.py in copyfile(src, dst, follow_symlinks)
     97     if _samefile(src, dst):
---> 98         raise SameFileError("{!r} and {!r} are the same file".fORMat(src, dst))
     99 

SameFileError: 1 and 2 are the same file

During handling of the above exception, another exception occurred:

NotImplementedError                       Traceback (most recent call last)
<ipython-input-27-ddb6bcd98254> in <module>()
      1 # python3 中会依次把异常记录下来
----> 2 mycopy(1, 2)

<ipython-input-26-7970d14296a0> in mycopy(source, dest)
      5         shutil.copy2(source, dest)
      6     except OSError: # We don't have permissions. More on this later
----> 7         raise NotImplementedError("automatic sudo injection")

NotImplementedError: automatic sudo injection

 

特性 4: 更好用的 OSError 子类

刚刚给你的代码其实不正确,OSError 实际上包含了很多类异常,比如权限不够,文件没找到,不是一个目录等,而我们默认是权限不够。你在 python2 中可能是这样来区分 OSError 的:


import errno
def mycopy(source, dest):
    try:
        shutil.copy2(source, dest)
    except OSError as e:
        if e.errno in [errno.EPERM, errno.EACCES]:
            raise NotImplementedError("automatic sudo injection")
        else:
            raise

 

python3 添加了大量的新 Exception 类型 Https://docs.python.org/3.4/library/exceptions.html#os-exceptions ,所以现在你可以这样做:


def mycopy(source, dest):
    try:
        shutil.copy2(source, dest)
    except PermissionError:
        raise NotImplementedError("automatic sudo injection")

 

特性 5: 一切皆迭代器

python2 中已经有迭代器了,然而 emmmm


def naivesum(N):
    A = 0
    for i in range(N + 1):
        A += i
    return A

naivesum(100000000) # 内存爆炸

当然,python2 中可以用 xrange 来解决这个问题,你还可以使用 itertools.izip, dict.itervalues 替代 zip 和 dict.values…… 在 python3 中,range,zip,dict.values 以及其它,都是返回迭代器,所以这对内存很友好。

如果你希望得到一个列表,要做的仅仅是在外层加一个 list,显示的声明永远比隐式地更好,你很难再写出一个吃内存的代码了。

 

特性 6: 不是一切都能比较

在 python2 中,你可以这么写


>>> max(['one', 2])
'one'

>>> "abc" > 123
True

>>> None > all
False

在 python3 中,这个非常 buggy 的特性被取消啦:


'one' > 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-55b5025c2335> in <module>()
----> 1 'one' > 2

TypeError: unorderable types: str() > int()

 

特性 7: yield from

如果你用 generator 的话,这个是一个非常好的特性。在以前,你是这么写代码的:


for i in gen():
    yield i

现在是这样


yield from gen()

 

没有看懂?来一个例子,比如这样,我们希望得到 [0, 0, 1, 1, 2, 2, ...] 的列表用于迭代,我们有以下写法:

 


# 蠢蠢的方法,直接生成对应的列表
def dup(n):
    A = []
    for i in range(n):
        A.extend([i, i])
    return A

# 不错的方法,使用 yield
def dup(n):
    for i in range(n):
        yield i
        yield i

# 更好的方法,使用 yield from
def dup(n):
    for i in range(n):
        yield from [i, i]

 

我们知道,迭代器的方式非常好,首先在内存上它很有优势,并且可以按需计算,每次只计算要用的值。如果你需要一个列表的时候,只需要在外层加一个 list,如果你需要切片 slicing,可以用 itertools.islice()

 

特性 8: asyncio

现在你可以用更方便的协程调用了


async def fetch(host, port):
    r, w = await open_connection(host, port)
    w,write(b'GET /HTTP/1.0\r\n\r\n')
    while (await r.readline()).decode('latin-1').strip():
        pass
    body = await r.read()
    return body

async def start():
    data = await fetch('Welcome to Python.org', 80)
    print(data.deode('utf-8'))

 

特性 9: 新的标准库

ipaddress 库


import ipaddress

print(ipaddress.ip_address('192.168.0.1'))
print(ipaddress.ip_address('2001:db8::'))
##> 192.168.0.1
##> 2001:db8::

 

functools.lrc_cache 装饰器


from functools import lru_cache
from urllib.error import HTTPError
import urllib.request

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except HTTPError:
        return 'Not Found'

for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
    pep = get_pep(n)
    print(n, len(pep))

get_pep.cache_info()
##> CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

 

enum 类


from enum import Enum

class Color(Enum):
    red = 1
    green = 2
    blue = 3

 

特性 10: Fun

听说你会中文编程


简历 = "knows python"
π = 2.1415936

 

类型标注


def f(a: int, b: int = 2) -> int:
    return 10

print(f.__annotations__)
##> {'return': <class 'int'>, 'a': <class 'int'>, 'b': <class 'int'>}

 

特性 11: Unicode 编码

这是新手遇到的最多的问题,为什么我的命令行输出是乱码?

python2 中的 str 是字节数组

python3 中的 str 是 unicode 字符串,只有 unicode 才能表示中文。

 

特性 12: 矩阵相乘

python3 中 @ 可以被重载了,所以用 numpy 中的矩阵乘法时可以这么来(我在 Tensorflow 中也经常这样写)


import numpy as np

a = np.array([[1, 0], [0, 1]])
b = np.array([[4, 1], [2, 2]])

# 旧写法
print(np.dot(a, b))
# 新写法
print(a @ b)

 

特性 13: pathlib

这是一个特别好用的面向对象路径处理库,以下是旧写法


import os

directory = "/etc"
filepath = os.path.join(directory, "hosts")

if os.path.exists(filepath):
    print('hosts exist')

 

更好的写法


from pathlib import Path

directory = Path("/etc")
filepath = directory / "hosts"

if filepath.exists():
    print('hosts exist')

 

--结束END--

本文标题: 13 个 python3 才能用的特性

本文链接: https://www.lsjlt.com/news/186217.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 13 个 python3 才能用的特性
    分享来源13 个 python3 才能用的特性 python3 于 2008 年发布,从最初的大割裂到现在,绝大多数的开源库已经使用 python3 来编写,并且已经迭代了五个大版本,最新的 python3.7 计划于 2018 年 6 ...
    99+
    2023-01-31
    能用 特性
  • C#10的13个特性
    常量的内插字符串 C# 10 允许使用在常量字符串初始化中使用插值, 如下 const string name = "Oleg"; const string greeting ...
    99+
    2024-04-02
  • 惊艳!Python3 的这几个特性
    距离官方放弃Python2的时间越来越近,很多项目也逐渐的开始放弃对Python2的支持,比如Django,IPython这些框架就走在了最前列,Python2完成了它的使命,在人工智能的新时代,Python2带来的问题不断地困扰开发者,...
    99+
    2023-01-31
    这几个 惊艳 特性
  • python的13个特性分别是什么
    python的13个特性分别是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。如果你是一个正在学习python的c、c++或者java程序员,或者你是刚开始学python...
    99+
    2023-06-02
  • Python3的这些新特性很方便
    概述   随着Python在机器学习和数据科学领域的应用越来越广泛,相关的Python库也增长的非常快。但是Python本身存在一个非常要命的问题,就是Python2和Python3,两个版本互不兼容,而且Github上Pytho...
    99+
    2023-01-31
    很方便 新特性
  • 你应该使用Python3里的这些新特性
    概述 由于Python2的官方维护期即将结束,越来越多的Python项目从Python2切换到了Python3。可是,在实际的工作中,我发现好多人都是在用Python2的思维去写Python3的代码,Python3给我们提供了很多新的、很...
    99+
    2023-01-31
    你应该 新特性
  • python3函数的高级特性有哪些
    本篇文章给大家分享的是有关python3函数的高级特性有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。python有哪些常用库python常用的库:1.requesuts;...
    99+
    2023-06-14
  • 5个实用的JavaScript新特性
    目录前言1.# 使用"Object.hasOwn"替代“in”操作符2.# 使用"#"声明私有属性3.# 超有用的&q...
    99+
    2024-04-02
  • IIS6.0的功能特性
    IIS6.0的容错式进程架构将Web站点和应用程序隔离到应用程序池中通过自动禁用在短时间内频繁发生故障的Web站点和应用程序,IIS 6.0可以保护服务器和其它应用程序的安全。回收一个工作进程时对客户机的TCP/IP连接加以维护,将Web服...
    99+
    2024-04-02
  • python3中函数的高级特性有哪些
    python3中函数的高级特性有哪些?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。Python主要用来做什么Python主要应用于:1、Web开发;2、数据科学...
    99+
    2023-06-14
  • 特殊符号如何才能用键盘打出来
    要打出特殊符号,可以使用以下方法:1. 使用ALT键组合:按住ALT键,在数字键盘上输入特殊符号的ASCII码(一些常见的符号的AS...
    99+
    2023-09-04
    键盘
  • 买一个云服务器要多久才能用
    购买云服务器通常需要支付一定的费用,具体的费用取决于所选择的服务提供商、云平台、带宽大小等因素。一些云服务器提供商的服务可能需要缴纳年费或者服务费用,而另一些则可能提供折扣或更优惠的价格。 如果您的计算机需要托管到云服务器上,那么您需要确...
    99+
    2023-10-27
    能用 要多久 服务器
  • CSS的三个特性是什么
    这篇文章给大家分享的是有关CSS的三个特性是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。 层叠(cascade)、继承(Inheritance)、特异性(Specific...
    99+
    2024-04-02
  • .NET 6中System.Text.Json的七个特性
    目录忽略循环引用序列化和反序列化通知 序列化支持属性排序使用Utf8JsonWriter编写JSONIAsyncEnumerable支持序列化支持流像DOM一样使用JSON...
    99+
    2024-04-02
  • CSS五个最新的特性怎么使用
    今天小编给大家分享一下CSS五个最新的特性怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一...
    99+
    2024-04-02
  • python3--面向对象的三大特性:封装,property,classmethod,staticmethod
    python中的封装隐藏对象的属性和实现细节,仅对外提供公共访问方式好处:1 将变化隔离2 便于使用3 提供复用性4 提高安全性封装原则1 将不需要对外提供的内容都隐藏起来2 把属性都隐藏,提供公共方法对其访问私有变量和私有方法在pytho...
    99+
    2023-01-30
    三大 面向对象 特性
  • 一篇文章带你学习Python3的高级特性(2)
    目录1.生成器2.迭代器总结1.生成器 # 一边循环一边计算的机制,称为生成器:generator; # 创建generator方法: # 1.把一个列表生成式的[]改成() num...
    99+
    2024-04-02
  • 一篇文章带你学习Python3的高级特性(1)
    目录1.切片2.迭代3.列表生成式总结1.切片 # 切片:取list或tuple的部分元素 nameList = ["Willard","ChenJD","ChenBao","Che...
    99+
    2024-04-02
  • 购买一个云服务器要多久才能用
    购买一个云服务器的价格取决于您选择的云服务器提供商的服务类型、规模和数据中心的可用容量。一般来说,云服务器的平均购买时间通常需要几周的时间才能收回购买成本。 如果您计划在一家公司的云服务器上托管数据,您可以使用该公司提供的数据迁移工具将数...
    99+
    2023-10-26
    能用 要多久 服务器
  • 买一个云服务器要多久才能用上
    在选择购买云服务器之前,我们需要考虑以下几个方面: 硬件配置:云服务器需要处理大量的数据和任务,因此需要选择具备高性能和稳定性的硬件配置。通常情况下,云服务器需要搭载英特尔至强处理器、NVIDIA显卡、Microsoft Azure I...
    99+
    2023-10-27
    要多久 服务器
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作