函数重载是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函数重载实例相关推荐

  1. python的id方法_python中id()函数的实用研究实例

    python中id()函数的实用研究实例 >>> a = 2.5 >>> b = 2.5 >>> c = b >>> a is ...

  2. python fields函数_Python函数详解

    # ------------------------------------一等函数------------------------------------ # 龟叔: 虽然我把函数定为一等对象,但是 ...

  3. python long函数_python函数

    一.函数的优点 使代码模块化 代码复用,减少冗余 保证了代码的一致性 python中的函数分为内置函数和自定义函数 内置函数: 如int(), str(), len(), range(), id(), ...

  4. change在python是什么函数_python函数基础

    python函数 函数的基本定义 函数参数 返回值 局部变量和全局变量 嵌套函数 匿名函数 高阶函数 递归 函数的基本定义 引子 现在你的老板让你写一个监控程序,24小时全年午无休的监控你们公司网站服 ...

  5. python中func自定义函数_Python函数之自定义函数作用域闭包

    一 前言 1.1 为什么要用函数 代码的组织结构更清晰,可读性好: 遇到重复的功能不需要重新编写代码,调用函数即可,代码不会冗余: 功能需要扩展时,只需要修改函数内容即可,实现统一管理,降低代码维护难 ...

  6. python labels函数_python——函数

    1.函数的创建 函数是可以调用的(可能带有参数,也可能无参),它执行某种行动并且返回一个值.一般来说,内建的callable函数可以用来判断函数是否可调用. 1 >>> import ...

  7. range函数python三个参数_python函数--range()方法

    range()方法 range()是python内置函数它能返回一系列连续增加的整数,它的工作方式类似于分片,可以生成一个列表对象. range函数大多数时常出现在for循环中,在for循环中可做为索 ...

  8. python nums函数_Python函数

    一.简介 函数是可重用的程序代码块.函数的作用,不仅可以实现代码的复用,更能实现代码的一致性.一致性指的是,只要修改函数的代码,则所有调用该函数的地方都能得到体现. 函数用关键字def来定义,def关 ...

  9. python not函数_python 函数

    1 为什么使用函数 在没有接触函数时,有时候需要将一个功能多次写,如果需要修改其中一个变量,则需要把所有实现该功能的代码一处一处改.不利于代码维护,代码量大了,组织结构也会很不清晰. 所以总结不使用函 ...

  10. python用def编写calsum函数_Python函数

    函数定义: 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. In [3]: def sum ...

最新文章

  1. git for c#, clone方法
  2. Spring 多数据源事务配置问题
  3. react 面试题 高级_高级前端面试题目大全(一)
  4. 那些神一样的学习技巧,专治各种不服!
  5. uva 10673 ——Play with Floor and Ceil
  6. 【转】C++/CLI简介(什么是C++/CLI) -------C++/CLI 编程系列一
  7. clob和blob是不是可以进行模糊查询_你知道什么是 MySQL 的模糊查询?
  8. 【学习Android NDK开发】Java通过JNI调用native方法
  9. 不小心合并了icloud通讯录_苹果手机怎么恢复通讯录联系人号码?原来方法竟如此简单!...
  10. Coding the Matrix作业Python Lab及提交方法
  11. java基础之 hashmap
  12. 转载一篇好用的ubuntu 16.04安装nvidia显卡驱动文章
  13. 音频处理工具 GoldWave / Cool Edit Pro
  14. java达内小发猫课程,详细说明
  15. 【Linux命令】Linux命令
  16. 第一台计算机如何工作原理,世界上第一台计算机是什么原理_世界上第一台计算机...
  17. html5 video/audio 监听事件属性及方法
  18. Java NIO全面详解(看这篇就够了)
  19. 【TypeScript】深入学习TypeScript命名空间
  20. 如何把音频转换成文本?不妨来试一下这三种方法吧

热门文章

  1. 小牛照片恢复软件_电脑移动硬盘U盘数据恢复SD卡照片文件软件修复开盘远程维修服务...
  2. Coloring Dominoes
  3. hash地址_到底什么是Hash?
  4. Linux socket / 端口复用
  5. 启明云端分享|一款方便、实用的且适用于ESP32/ESP8266的USB-TTL转接板开发工具推荐
  6. 字少事大|两张表格教你快速选择适合的MCU进行物联网开发
  7. 添加vlan后无法上网_KTV多SSID绑定VLAN实用案例,值得一看的干货
  8. mysql insert into select大量数据插入比较慢_史上最全MySQL锁机制
  9. Python基础(偏函数)
  10. 二分图的最佳完美匹配(模板)