如何在Python中区分两种类似的函数或方法?

如何在Python中区分两种类似的函数或方法?,python,function,Python,Function,例如,在python中,有两种函数或方法具有不同类型的输入参数 def fp(ps): print(ps, "ps should be a cartesian points array") def fb(bs): print(bs, "bs should be a barycentric points array") 我将把上述一个或多个functin对象传递给另一个函数,例如: def process(f0, f1): pri

例如,在python中,有两种函数或方法具有不同类型的输入参数

def fp(ps):
    print(ps, "ps should be a cartesian points array")

def fb(bs):
    print(bs, "bs should be a barycentric points array")
我将把上述一个或多个functin对象传递给另一个函数,例如:

def process(f0, f1):
    print("I want to call `f0` and `f1`!")
    print(" `f0(ps)` or `f0(bs)`?")
    print(" `f1(ps)` or `f1(bs)`?")

是否有一种简洁的方法来决定我应该传递哪些参数(
ps
bs
)来调用
f0
f1
Python装饰器可以解决我的问题,如下所示:

from functools import wraps

def cartesian(func):
    @wraps(func)
    def add_attribute(*args, **kwargs):
        return func(*args, **kwargs)
    add_attribute.__dict__['coordtype'] = 'cartesian' 
    return add_attribute 

def barycentric(func):
    @wraps(func)
    def add_attribute(*args, **kwargs):
        return func(*args, **kwargs)
    add_attribute.__dict__['coordtype'] = 'barycentric' 
    return add_attribute 

@cartesian
def fp(ps):
    print('This function need a cartesian type input!')

@barycentric
def fb(bs):
    print('This function need a barycentric type input!')

def process(f0, f1):
    bs = ...
    ps = ...
    if f0.coordtype == 'cartesian':
        val0 = f0(ps)
    elif f0.coordtype == 'barycentric':
        val0 = f0(bs)

    if f1.coordtype == 'cartesian':
        val1 = f1(ps)
    elif f1.coordtype == 'barycentric':
        val1 = f1(bs)
    ... # do something for val0 and val1

然后,我只需要一个带有简单接口的
过程
实现。

如果两者都是数组,并且不能按其类型进行区分,那么这是不可能的。人类必须这样做。
过程
应该将其定义为其接口的一部分。例如,“
f0
需要是一个可调用的函数,它接受一个点数组作为参数。
process
的调用方需要遵循接口,动态地解决这一问题不是
process
的工作。在我的应用程序中,
process
在调用这两种函数后,会对它们执行相同的操作。当然,我可以添加更多的参数来告诉
process
我想要什么样的调用,但是这会使
process
的界面太复杂。不,不要添加更多的参数。只需定义每个参数是什么。它可以是接受点值数组的可调用函数,也可以是接受重心数组的可调用函数。把它们看作是一种类型。“接受点数组的可调用”是一种类似于
str
int
的类型。你不会让一个函数接受随机类型,然后决定如何处理它们;该函数定义了它需要的类型。在我的应用程序中,我可能会将三个或更多这样的函数传递给
进程
,处理对这些函数的调用可能会非常麻烦。