python中的函数签名
Function signature in python
在C++中,只要签名不同,就可以创建两个同名函数。因此,例如myfunc(int x)
与myfunc(float x)
不同。在python中,你不能这样做,那么,你需要用不同的名称定义函数吗?或者有更好的方法来处理这种情况吗?
在Python3.4+中,您可以使用functools.singledispatch
装饰器,它允许您定义一个通用函数,然后针对它注册类型化实现。
从文档
通用功能:
>>> from functools import singledispatch
>>> @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)
早期版本的Python没有内置的解决方案,但GuidovanRossum在博客中介绍了一个使用decorator的python2解决方案。(编辑:pypi上还有一个用于pythons 2.6-3.3的3.4功能的后台端口)
编辑:当然,使用Python的优点之一是,相同的代码通常可以处理int和float,而无需对类型进行显式调度,这也是最近才添加该功能的原因之一。
Python并不真正关心参数是整数还是浮点。它是动态类型的。例如,你可以这样做:
def SquareMe(num):
return num**2
您可以用任何数字(int
、float
、complex
…)调用此函数
也可以这样做:
def MultMe(data):
return data*2
这将适用于数字、字符串(!)、列表(!!)、NumPy数组以及任何可以与数字相乘的数组(如果某个类提供了此方法)。
在python中,你只需要创建一个方法,但你可以检查哪些参数可以被传递,如果它们是不同的参数(即:一个是float,另一个是int),那么你可以区分两个函数。在代码中,这看起来像:
def myfunc(*args):
# do something
# when you call the method
myfunc(a1, a2, k1=a3, k2=a4)
# you get:
args = (a1, a2)
kwds = {'k1':a3, 'k2':a4}
#So now lets recreate myfunc to check arguments
def myfunc(*args):
if isinstance(args[0], str): #This is where you determine argument type
# do what you want to do if argument is string
elif isinstance(args[1], int):
# do what you want to do if argument is an int
正如ForceBru所说,Python并不真正关心参数类型,所以如果你关心,你可以自己处理:
def myfunc(x):
if(isinstance(x,int)):
print (x, 'int') # as myfunc(int x)
if(isinstance(x,float)):
print (x, 'float') # as myfunc(float x)
myfunc(10) # 10 int
myfunc(10.2) # 10.2 float
myfunc ("A") #
您可以让函数本身根据参数的类型和数量做不同的事情。
def f (a):
if type (a) == 'float' or type (a) == 'int':
...
if type (a) == 'list':
...
if type (a) == 'dict':
...
相关文章:
- 从python中调用C++函数并获取返回值
- 从python调用openMP共享库时,未定义opnMP函数
- 有没有一个 c++ gmp 库函数与 python gmpy2 库 divm(..) 函数相同?
- C++中是否有任何函数等同于python中字典的get函数?
- 如何将 c++ get 函数代码转换为 opencv 算法中使用的 python
- 是否可以使用 libclang python 解析 cpp 文件中没有标头的函数原型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针
- 使用C++指针调用 python 函数
- 如何将 Python 字符串传递给 C++ (extern C) 函数
- 如何通过python方法和kwargs来提升python的c++函数和调用
- C++ python 中的函数返回数字而不是字符串
- 通过Cython对Python的基本C++函数
- 你如何决定将C++和/或 python 中的成员函数表示为静态?
- 使用 pybind11 调用 Python 函数时避免复制输入数据
- 从python调用C++函数,使用cython,使用cythonize
- 从 C++ 函数与 Python 函数返回的不一致值用于偏斜正态分布
- 在C++中实现类似 python "map"函数的问题:调用类成员函数
- Python 的 exec() 函数的 C++ 版本
- 如何使用 pybind11 将 python 函数保存到静态 c++ 容器中?
- 在 cpp 中嵌入 python:如何获取指向 python 函数(而不是 PyObject)的 C 指针?