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

歡迎訪問 生活随笔!

生活随笔

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

python

python 重载id函数_Python函数重载实例

發布時間:2024/10/8 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 重载id函数_Python函数重载实例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

函數重載是Python中的稀罕東西。注意觀察@functools.singledispatch 的使用;

下面貼出functools模塊函數的使用示例,及簡短描述。來自如下文檔。

Python ? 3.6.0a4 Documentation ? The Python Standard Library ? 10. Functional

10.2. functools — Higher-order functions and operations on callable objects

# 10.2. functools — Higher-order functions and operations on callable objects

import functools

import locale

from urllib import request

# functools.cmp_to_key(func) 轉換舊的key函數為新函數

d = sorted('ABCDEFG', key=functools.cmp_to_key(locale.strcoll))

print(d)

# LRU (least recently used) cache

@functools.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 request.urlopen(resource) as s:

return s.read()

except Exception:

return 'Not Found'

#for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:

for n in 8, 290:

pep = get_pep(n)

print(n, len(pep))

print(get_pep.cache_info())

# 排序比較。

# 提供__lt__(), __le__(), __gt__(), or __ge__()之一。

# 再提供__eq__() 方法

@functools.total_ordering

class Student:

def _is_valid_operand(self, other):

return (hasattr(other, "lastname") and

hasattr(other, "firstname"))

def __eq__(self, other):

if not self._is_valid_operand(other):

return NotImplemented

return ((self.lastname.lower(), self.firstname.lower()) ==

(other.lastname.lower(), other.firstname.lower()))

def __lt__(self, other):

if not self._is_valid_operand(other):

return NotImplemented

return ((self.lastname.lower(), self.firstname.lower()) <

(other.lastname.lower(), other.firstname.lower()))

# functools.partial(func, *args, **keywords)

basetwo = functools.partial(int, base=2)

basetwo.__doc__ = 'Convert base 2 string to an int.'

print(basetwo('10010'))

# class functools.partialmethod(func, *args, **keywords)

# partialmethod 設計用于方法定義

class Cell(object):

def __init__(self):

self._alive = False

@property

def alive(self):

return self._alive

def set_state(self, state):

self._alive = bool(state)

set_alive = functools.partialmethod(set_state, True)

set_dead = functools.partialmethod(set_state, False)

c = Cell()

print(c.alive)

c.set_alive()

print(c.alive)

# functools.reduce(function, iterable[, initializer])

# 累加

# reduce 減少; 縮小; 使還原; 使變弱;

# 此處是累加的意思

d= functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],100)

print(d)

# 函數重載

@functools.singledispatch

def fun(arg, verbose=False):

if verbose:

print("Let me just say,", end=" ")

print(arg)

@fun.register(int)

def _(arg, verbose=False):

if verbose:

print("Strength in numbers, eh?", end=" ")

print(arg)

@fun.register(list)

def _(arg, verbose=False):

if verbose:

print("Enumerate this:")

for i, elem in enumerate(arg):

print(i, elem)

print('函數重載')

fun("test.", verbose=True)

fun(42, verbose=True)

fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)

fun({'a':'txt','b':'dat'}, verbose=True)

'''

函數重載

Let me just say, test.

Strength in numbers, eh? 42

Enumerate this:

0 spam

1 spam

2 eggs

3 spam

Let me just say, {'b': 'dat', 'a': 'txt'}

'''

# 默認partial對象沒有__name__和__doc__, 這種情況下,

# 對于裝飾器函數非常難以debug.使用update_wrapper(),

# 從原始對象拷貝或加入現有partial對象

# 它可以把被封裝函數的__name__、 module 、__doc__和 __dict__

# 都復制到封裝函數去(模塊級別常量WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)

# 缺省是模塊級別常量 WRAPPER_ASSIGNMENTS

# 賦給包裝器__module__, __name__, __qualname__, __annotations__ 和 __doc__

# WRAPPER_UPDATES 更像包裝器的__dict__

# functools.update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

# 更新包裝器函數以便更像被包裝的函數

from functools import update_wrapper

def wrap2(func):

def call_it(*args, **kwargs):

"""wrap func: call_it2"""

print('before call')

return func(*args, **kwargs)

return update_wrapper(call_it, func)

@wrap2

def hello2():

"""test hello"""

print('hello world2')

hello2()

print(hello2.__name__)

print(hello2.__doc__)

# @functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

from functools import wraps

def my_decorator(f):

@wraps(f)

def wrapper(*args, **kwds):

print('Calling decorated function')

return f(*args, **kwds)

return wrapper

@my_decorator

def example():

"""Docstring"""

print('Called example function')

example()

print(example.__name__)

print(example.__doc__)

總結

以上是生活随笔為你收集整理的python 重载id函数_Python函数重载实例的全部內容,希望文章能夠幫你解決所遇到的問題。

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