Python 函数如何实现“重载”

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_43773093/article/details/88535763

在这里插入图片描述
文章地址:Python 函数实现重载

单分派泛函数

假如你想在交互模式下打印出美观的对象,那么标准库中的 pprint.pprint() 函数或许是一个不错的选择。但是,如果你想 DIY 一个自己看着舒服的打印模式,那么你很可能会写一长串的 if/else 语句,来判断传进来对象的类型。

def fprint(obj):
	if isinstance(obj, list):
    	print_list(obj)
	elif isinstance(obj, tuple):
    	print_tuple(obj)
	elif isinstance(obj, str):
    	print_str(obj)

这样做固然没有错,但是太多的 if 语句使得代码不易扩展,而且代码可读性也要大打折扣。

他山之石

首先让我们先来看看其他语言会怎样处理这样的问题:

Java 支持方法重载,我们可以编写同名方法,但是这些方法的参数要不一样,主要体现在参数个数与参数类型方面。下面我们重载了 fprint() 这个静态方法,调用 fprint() 方法时,如果传进来的参数是字符串,那么就调用第一个方法;如果传进来的参数是整型,那么就调用第二个方法。

public class Overriding {
    // 方法一
    public static void fprint(String Astring){
        System.out.println("我是一个字符串");
        System.out.println(Astring);
    }
    // 方法二
    public static void fprint(int Aint){
        System.out.println("我是一个整型");
        System.out.println(Aint);
    }
    public static void main(String[] args){
        fprint("Hello, Python.");
        fprint(666);
    }
}

输出结果:

我是一个字符串
Hello, Python.
我是一个整型
666

Python 的解决方案

Python 通过单分派泛函数部分支持了方法重载。

官方文档是这样定义泛函数以及单分派函数的:

A generic function is composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm. When the implementation is chosen based on the type of a single argument, this is known as single dispatch.

也就是说单分派泛函数(single dispatch)可以根据第一个参数的类型,来判断执行哪一个函数体。

那么我们使用 singledispatch 重写上面的例子:

  1. 首先我们要从functools 中导入 singledispatch
from functools import singledispatch
  1. singledispatch 是作为装饰器使用的函数。装饰器是 Python 中的语法糖,@singledispatch 实际上相当于 singledispatch(fprint),这里我们并不关心 singledispatch 的内部实现,我们只需知道 singledispatch 可以实现分派机制就行。NotImplemented 是 Python 中的内置常量,提醒我们没有实现某个功能。注意这与 NotImplementedError 有天壤之别,后者会导致异常出现,终止程序。当调用 fprint() 函数时,如果参数的类型没有被注册,那么默认会执行使用 @singledispatch 装饰的函数。

    @singledispatch
    def fprint(obj):
        return NotImplemented
    
  2. 我们使用 @<主函数名>.register(type) 来装饰专门函数。要注意分派函数可以有任意多个参数,但是调用函数时执行哪一部分功能只由函数第一个参数决定,也就是由 register 中声明的参数类型决定。 而对于专门函数来说,函数名是无关紧要的,使用 _ 更加简洁明了。

@singledispatch
def fprint(obj):
    return NotImplemented


@fprint.register(str)
def _(obj):
    print('我是一个字符串')
    print(obj)
    

@fprint.register(int)
def _(obj):
    print('我是一个整型')
    print(obj)    
  1. Python 3.7 中新增了一个功能:即使用 type annotions 来注明第一个参数的类型。打印结果,与使用装饰器参数得到的结果相同。
@fprint.register
def _(obj:str):
    print('我是一个字符串')
    print(obj)

最后我们对代码进行测试,结果符合我们的预期:

>>> fprint('Nice to meet you, Java')
我是一个字符串
Nice to meet you, Java
>>> fprint(999)
我是一个整型
999
>>> fprint((12, 4))
NotImplemented

更复杂的例子

上面就是 single dispatch 的基本用法,下面让我们看一个稍微复杂点的例子。

想象,你需要一个自定义的打印函数,又不想过多地使用 if/else 分支,那么你可以应用刚学到的 single dispatch 来解决问题。

  1. 首先要导入我们需要的库,这里我们用到了几个抽象基类,整数 Integral 和 可变序列 MutableSequence。使用抽象基类,可以使得我们的程序可拓展性更强。使用 Integral 注册的函数不仅支持常规的 int 类型,还支持Integral 的子类或者注册为 Integral 的虚拟子类,甚至可以支持实现了 Integral “协议” 的类型。这充分体现了Python “鸭子类型” 的强大之处。可变序列也是如此,不仅支持常规的 list 类型,还支持符合要求的自定义类型。
from functools import singledispatch
from numbers import Integral
from collections.abc import MutableSequence
  1. 其次,我们定义默认行为。即没有被注册的类型,会执行下面的函数。这里,为了方便起见,我们直接打印对象的类型与内容。
@singledispatch
def pprint(obj):
    print(f'({obj.__class__.__name__}) {obj}')
>>> pprint('微信公众号:Python高效编程')
(str) 微信公众号:Python高效编程
  1. 第一个函数使用了 type annotations,注册为 Integral 类型。第二个函数注册为 float 类型,打印的时候小数点后保留两位。
@pprint.register
def _(obj:Integral):
    print(f'({obj.__class__.__name__}) {obj}')
 
    
@pprint.register(float)
def _(obj):
    print(f'({obj.__class__.__name__}) {obj:.2f}')
>>> pprint(666)
(int) 666
>>> pprint(66.6457)
(float) 66.65
  1. 我们还可以通过堆积(类型注册)装饰器,来实现对多种类型的支持。下面这个函数就支持三种类型,分别是元组,集合,可变序列。
@pprint.register(tuple)
@pprint.register(set)
@pprint.register(MutableSequence)
def _(obj):
    print(f'{"-"*7}{obj.__class__.__name__}{"-"*8}')
    print(f'index   type      value')
    for index, value in enumerate(obj):
        print(f'{index:^6}->{type(value).__name__:<8}: {value}')
>>> a = [[1, 3, 4], 'name', 5, 6]
>>> pprint(a)
-------list--------
index   type      value
  0   ->list    : [1, 3, 4]
  1   ->str     : name
  2   ->int     : 5
  3   ->int     : 6
>>> b = {1, 3, 4}
>>> pprint(b)
-------set--------
index   type      value
  0   ->int     : 1
  1   ->int     : 3
  2   ->int     : 4
  1. 最后我们支持了字典类型:
@pprint.register(dict)
def _(obj):
    print(f'{"-"*7}{obj.__class__.__name__}{"-"*8}')
    print('     key            value')
    for k, v in sorted(obj.items()):
        print(f'({type(k).__name__}){k:<6} -> ({type(v).__name__}){v:<6}')
>>> a = {'part1': "Python高效编程",'part2':'关注转发', 'part3': 666}
>>> pprint(a)
-------dict--------
     key            value
(str)part1  -> (str)Python高效编程
(str)part2  -> (str)关注转发  
(str)part3  -> (int)666  

讲完上面的例子,我们再补充一个小用法:

  • 假如我们想知道 pprint() 函数支持哪些类型,我们该怎么做呢?

pprint.registry 返回类型与函数地址的键值对,调用 keys() 方法获取 pprint() 函数支持的类型。

>>> pprint.registry.keys()
dict_keys([<class 'object'>,
           <class 'numbers.Integral'>,
           <class 'float'>, 
           <class 'collections.abc.MutableSequence'>,
           <class 'set'>, <class 'tuple'>, <class 'dict'>])

总结

这篇文章,我们从一个简单例子切入,介绍了 singledispatch 的简单用法与使用案例。如果你发现你的代码需要使用分派函数,不妨尝试这种代码风格。如果想深入了解 singledispatch 的用法,不妨去 PEP 443functools docs 一探究竟。
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43773093/article/details/88535763