int area(int length, int breadth) {
return length * breadth;
}
float area(int radius) {
return 3.14 * radius * radius;
}
Python猫注:这里说 Python 不支持函数重载,指的是在不用语法糖的情况下。使用 functools 库的 singledispatch 装饰器,Python 也可以实现函数重载。原文作者在文末的注释中专门提到了这一点。
def area(radius):
return 3.14 * radius ** 2
>>> locals()
{
...
'area': <function area at 0x10476a440>,
...
}
Function
的类,它可以封装任何函数,并通过重写的__call__
方法来调用该函数,还提供了一个名为key
的方法,该方法返回一个元组,使该函数在整个代码库中是唯一的。from inspect import getfullargspec
class Function(object):
"""Function类是对标准的Python函数的封装"""
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
"""当像函数一样被调用时,它就会调用被封装的函数,并返回该函数的返回值"""
return self.fn(*args, **kwargs)
def key(self, args=None):
"""返回一个key,能唯一标识出一个函数(即便是被重载的)"""
# 如果不指定args,则从函数的定义中提取参数
if args is None:
args = getfullargspec(self.fn).args
return tuple([
self.fn.__module__,
self.fn.__class__,
self.fn.__name__,
len(args or []),
])
key
函数返回一个元组,该元组唯一标识了代码库中的函数,并且记录了:__call__
方法会调用被封装的函数,并返回计算的值(这没有啥特别的)。这使得Function
的实例可以像函数一样被调用,并且它的行为与被封装的函数完全一样。def area(l, b):
return l * b
>>> func = Function(area)
>>> func.key()
('__main__', <class 'function'>, 'area', 2)
>>> func(3, 4)
12
area
被封装在Function
中,并被实例化成func
。key() 返回一个元组,其第一个元素是模块名__main__
,第二个是类<class 'function'>
,第三个是函数名area
,而第四个则是该函数接收的参数数量,即 2。class Namespace(object):
"""Namespace是一个单例类,负责保存所有的函数"""
__instance = None
def __init__(self):
if self.__instance is None:
self.function_map = dict()
Namespace.__instance = self
else:
raise Exception("cannot instantiate a virtual Namespace again")
@staticmethod
def get_instance():
if Namespace.__instance is None:
Namespace()
return Namespace.__instance
def register(self, fn):
"""在虚拟的命名空间中注册函数,并返回Function类的可调用实例"""
func = Function(fn)
self.function_map[func.key()] = fn
return func
Namespace
类有一个register
方法,该方法将函数 fn 作为参数,为其创建一个唯一的键,并将函数存储在字典中,最后返回封装了 fn 的Function
的实例。这意味着 register 函数的返回值也是可调用的,并且(到目前为止)它的行为与被封装的函数 fn 完全相同。def area(l, b):
return l * b
>>> namespace = Namespace.get_instance()
>>> func = namespace.register(area)
>>> func(3, 4)
12
import time
def my_decorator(fn):
"""这是一个自定义的函数,可以装饰任何函数,并打印其执行过程的耗时"""
def wrapper_function(*args, **kwargs):
start_time = time.time()
# 调用被装饰的函数,并获取其返回值
value = fn(*args, **kwargs)
print("the function execution took:", time.time() - start_time, "seconds")
# 返回被装饰的函数的调用结果
return value
return wrapper_function
@my_decorator
def area(l, b):
return l * b
>>> area(3, 4)
the function execution took: 9.5367431640625e-07 seconds
12
overload
的装饰器,它能在虚拟命名空间中注册函数,并返回一个可调用对象。def overload(fn):
"""用于封装函数,并返回Function类的一个可调用对象"""
return Namespace.get_instance().register(fn)
overload
装饰器借助命名空间的 .register() 函数,返回 Function 的一个实例。现在,无论何时调用函数(被 overload 装饰的),它都会调用由 .register() 函数所返回的函数——Function 的一个实例,其 call 方法会在调用期间使用指定的 args 和 kwargs 执行。def get(self, fn, *args):
"""从虚拟命名空间中返回匹配到的函数,如果没找到匹配,则返回None"""
func = Function(fn)
return self.function_map.get(func.key(args=args))
def __call__(self, *args, **kwargs):
"""重写能让类的实例变可调用对象的__call__方法"""
# 依据参数,从虚拟命名空间中获取将要调用的函数
fn = Namespace.get_instance().get(self.fn, *args)
if not fn:
raise Exception("no matching function found.")
# 调用被封装的函数,并返回调用的结果
return fn(*args, **kwargs)
overload
装饰器进行装饰。@overload
def area(l, b):
return l * b
@overload
def area(r):
import math
return math.pi * r ** 2
>>> area(3, 4)
12
>>> area(7)
153.93804002589985
原作者注:从 Python 3.4 开始,Python 的 functools.singledispatch 支持函数重载。从 Python 3.8 开始,functools.singledispatchmethod 支持重载类和实例方法。感谢 Harry Percival 的指正。
getfullargspec
函数和我们的想象。使用前文的思路,你可能会实现出一个更整洁、更干净、更高效的方法,所以,请尝试实现一下吧。# 模块:overload.py
from inspect import getfullargspec
class Function(object):
"""Function is a wrap over standard python function
An instance of this Function class is also callable
just like the python function that it wrapped.
When the instance is "called" like a function it fetches
the function to be invoked from the virtual namespace and then
invokes the same.
"""
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
"""Overriding the __call__ function which makes the
instance callable.
"""
# fetching the function to be invoked from the virtual namespace
# through the arguments.
fn = Namespace.get_instance().get(self.fn, *args)
if not fn:
raise Exception("no matching function found.")
# invoking the wrapped function and returning the value.
return fn(*args, **kwargs)
def key(self, args=None):
"""Returns the key that will uniquely identifies
a function (even when it is overloaded).
"""
if args is None:
args = getfullargspec(self.fn).args
return tuple([
self.fn.__module__,
self.fn.__class__,
self.fn.__name__,
len(args or []),
])
class Namespace(object):
"""Namespace is the singleton class that is responsible
for holding all the functions.
"""
__instance = None
def __init__(self):
if self.__instance is None:
self.function_map = dict()
Namespace.__instance = self
else:
raise Exception("cannot instantiate Namespace again.")
@staticmethod
def get_instance():
if Namespace.__instance is None:
Namespace()
return Namespace.__instance
def register(self, fn):
"""registers the function in the virtual namespace and returns
an instance of callable Function that wraps the function fn.
"""
func = Function(fn)
specs = getfullargspec(fn)
self.function_map[func.key()] = fn
return func
def get(self, fn, *args):
"""get returns the matching function from the virtual namespace.
return None if it did not fund any matching function.
"""
func = Function(fn)
return self.function_map.get(func.key(args=args))
def overload(fn):
"""overload is the decorator that wraps the function
and returns a callable object of type Function.
"""
return Namespace.get_instance().register(fn)
from overload import overload
@overload
def area(length, breadth):
return length * breadth
@overload
def area(radius):
import math
return math.pi * radius ** 2
@overload
def area(length, breadth, height):
return 2 * (length * breadth + breadth * height + height * length)
@overload
def volume(length, breadth, height):
return length * breadth * height
@overload
def area(length, breadth, height):
return length + breadth + height
@overload
def area():
return 0
print(f"area of cuboid with dimension (4, 3, 6) is: {area(4, 3, 6)}")
print(f"area of rectangle with dimension (7, 2) is: {area(7, 2)}")
print(f"area of circle with radius 7 is: {area(7)}")
print(f"area of nothing is: {area()}")
print(f"volume of cuboid with dimension (4, 3, 6) is: {volume(4, 3, 6)}")