美文网首页
Python3.8新特性

Python3.8新特性

作者: loick | 来源:发表于2019-11-01 20:42 被阅读0次
赋值表达式
if (n:=len(arr)) > 0:
    # do something
仅位置参数(Positional-only parameters)

Python的函数参数有 positional, keyword, or keyword-only,现在新版本加入了新的类型,它的语法是/,把/放在函数定义参数的中间,左边的参数表示位置参数,不能用做keyword arguments。
在下面这个例子中,a、b是仅位置参数,c, d可以是位置参数或关键字参数,e, f必须是关键字参数

def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

下面是一个正确的调用

f(10, 20, 30, d=40, e=50, f=60)
f-strings

让字符串输出更轻松,易读。语法是这样的f'{expr=}expr是变量名,通过这个语法最后得到的就是expr=expr.val, 举个例子

>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"

>>> delta = date.today() - member_since
>>> f'{user=!s}  {delta.days=:,d}'
'user=eric_idle  delta.days=16,075'
functools

functools.lru_cache()可以直接用做一个装饰器,而不是函数返回了(不用带())。下面的用法都是支持的

@lru_cache
def f(x):
    ...

@lru_cache(maxsize=256)
def f(x):
    ...

functools.cached_property()装饰器, 缓存计算属性直到对象销毁。

import functools

class Dataset:
   def __init__(self):
      # do something

   @functools.cached_property
   def variance(self):
      # 
math

新函数math.dist()计算两个点的欧几里得距离

import math

p1 = (0, 0)
p2 = (3, 4)
math.dist(p1, p2)  # 5.0

新函数math.perm(), math.comb()可以计算排列组合

>>> math.perm(10, 3)    # Permutations of 10 things taken 3 at a time
720
>>> math.comb(10, 3)    # Combinations of 10 things taken 3 at a time
120
更多

What’s New In Python 3.8

相关文章

网友评论

      本文标题:Python3.8新特性

      本文链接:https://www.haomeiwen.com/subject/uxmqbctx.html