日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

流畅的Python 5. 函数

發布時間:2024/7/5 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 流畅的Python 5. 函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 函數對象
    • 2. 高階函數
    • 3. 匿名函數
    • 4. 可調用函數
    • 5. 定位參數、僅限關鍵字參數
    • 6. 獲取參數信息
    • 7. 函數注解
    • 8. 支持函數式編程的包

1. 函數對象

def factorial(n):'''returns n! n的階乘'''return 1 if n < 2 else n * factorial(n - 1)print(factorial(42)) print(factorial.__doc__) # returns n! n的階乘 print(type(factorial)) # <class 'function'>fact = factorial print(fact) # <function factorial at 0x0000021512868EA0> print(fact(4)) # 24 print(list(map(factorial, range(11)))) # [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

2. 高階函數

  • 接受函數作為參數,如 map,sorted
fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=len)) # 按長度排序 # ['fig', 'apple', 'cherry', 'banana', 'raspberry', 'strawberry']def reveres(word):return word[::-1]print(reveres("michael")) # leahcim print(sorted(fruits, key=reveres)) # 逆序字符串排序 # ['banana', 'apple', 'fig', 'raspberry', 'strawberry', 'cherry']

3. 匿名函數

  • lambda
print(sorted(fruits, key=lambda w : w[::-1])) # ['banana', 'apple', 'fig', 'raspberry', 'strawberry', 'cherry']

4. 可調用函數

  • 對象是否可調用:callable()
print([callable(obj) for obj in (abs, str, 13, factorial)]) # [True, True, False, True]
  • 任意對象實現可調用:實現 __call__()
import randomclass BingoCage:def __init__(self, items):self._items = list(items)random.shuffle(self._items)def pick(self):try:return self._items.pop()except IndexError:raise LookupError("pick from empty BingoCage")def __call__(self):return self.pick()arr = [1, 2, 3, 4, 5] bc = BingoCage(arr); print(bc._items) # [1, 4, 3, 5, 2] print(bc.pick()) # 2 print(bc._items) # [1, 4, 3, 5] print(bc()) # 5, bc 實現了 __call_() 可調用 print(bc._items) # [1, 4, 3] print(callable(bc)) # True

5. 定位參數、僅限關鍵字參數

def tag(name, *content, cls=None, **attrs):"""生成一個或多個HTML標簽"""if cls is not None:attrs['class'] = clsif attrs:attr_str = ''.join(' %s="%s"' % (attr, value)for attr, valuein sorted(attrs.items()))else:attr_str = ''if content:return '\n'.join('<%s%s>%s</%s>' %(name, attr_str, c, name) for c in content)else:return '<%s%s />' % (name, attr_str)print(tag('br')) # <br /> print(tag('p', 'hello')) # <p>hello</p> print(tag('p', 'hello', 'world')) # 第一個參數后的任意個 參數 被 *content 捕獲,存入元組 # <p>hello</p> # <p>world</p> print(tag('p', 'hello', id=33, pid=24)) # 沒有明確指定名稱的關鍵字參數被 **attrs 捕獲,存入字典 # <p id="33" pid="24">hello</p> print(tag('p', 'hello', 'world', id=33, cls='sidebar', pid=24)) # cls 參數只能作為關鍵字參數 # <p class="sidebar" id="33" pid="24">hello</p> # <p class="sidebar" id="33" pid="24">world</p> print(tag(cont='testing', name="img")) # <img cont="testing" /> my_tag = {'name': 'img', 'title': 'Sunset Boulevard','src': 'sunset.jpg', 'cls': 'framed'} print(tag(**my_tag)) # ** 字典中所有元素作為單個參數傳入,同名鍵綁定到對應具名參數,余下被 **attrs 捕獲 # <img class="framed" src="sunset.jpg" title="Sunset Boulevard" /> def f(a, *c, b):return a, bprint(f(1, b=2)) # (1, 2) print(f(1, 2, b=3)) # (1, 3) b= 必須寫,因為前面有 * 參數# print(f(1, 2)) # f() takes 1 positional argument but 2 were givendef f1(a, b, *c):return a, bprint(f1(1, b=2)) # (1, 2) print(f1(1, 2)) # (1, 2) print(f1(1, 2, 3)) # (1, 2)

6. 獲取參數信息

from inspect import signature sig = signature(tag) print(sig) # (name, *content, cls=None, **attrs)my_tag = {'name': 'img', 'title': 'Sunset Boulevard','src': 'sunset.jpg', 'cls': 'framed'} bound_args = sig.bind(**my_tag) print(bound_args) # <BoundArguments (name='img', cls='framed', attrs={'title': 'Sunset Boulevard', 'src': 'sunset.jpg'})> del my_tag['name'] bound_args = sig.bind(**my_tag) # TypeError: missing a required argument: 'name'

7. 函數注解

  • 對參數,返回值進行注釋,解釋器不做檢查
def clip(text: str, max_len: 'int > 0' = 80) -> str:passprint(clip.__annotations__) # 一個字典 # 注解可以是 類 或者 字符串 # {'text': <class 'str'>, 'max_len': 'int > 0', 'return': <class 'str'>} sig = signature(clip) print(sig) # (text: str, max_len: 'int > 0' = 80) -> str print(sig.return_annotation) # <class 'str'> for param in sig.parameters.values():print(param.name, " ", param.annotation, " ", param.default) # text <class 'str'> <class 'inspect._empty'> # max_len int > 0 80

8. 支持函數式編程的包

  • operator
from functools import reducedef fact(n):return reduce(lambda a, b: a * b, range(1, n + 1))print(fact(5))from operator import muldef fact1(n):return reduce(mul, range(1, n + 1))print(fact1(5)) metro_data = [('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)), ] from operator import itemgetter import operator for city in sorted(metro_data, key=itemgetter(1)):print(city) # 按照 索引 1 排序cc_name = itemgetter(1, 0) for city in metro_data:print(cc_name(city)) # ('JP', 'Tokyo') # ('IN', 'Delhi NCR') # ('MX', 'Mexico City') # ('US', 'New York-Newark') # ('BR', 'Sao Paulo')print([name for name in dir(operator) if not name.startswith('_')]) # ['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf', # 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand', # 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul', 'index', # 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift', 'is_', 'is_not', # 'isub', 'itemgetter', 'itruediv', 'ixor', 'le', 'length_hint', 'lshift', # 'lt', 'matmul', 'methodcaller', 'mod', 'mul', 'ne', 'neg', 'not_', 'or_', # 'pos', 'pow', 'rshift', 'setitem', 'sub', 'truediv', 'truth', 'xor'] from operator import methodcallers = 'the time has come' upcase = methodcaller('upper') # 調用指定的方法 'upper' print(upcase(s)) # THE TIME HAS COME connect = methodcaller('replace', ' ', '-') print(connect(s)) # the-time-has-come from operator import mul from functools import partialtriple = partial(mul, 3) print(triple(7)) # 21 print(list(map(triple, range(1, 10)))) # [3, 6, 9, 12, 15, 18, 21, 24, 27] 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的流畅的Python 5. 函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。