“超载"的最佳方式python中的函数? [英] Best way to "overload" function in python?

查看:61
本文介绍了“超载"的最佳方式python中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中做这样的事情:

I am trying to do something like this in python:

def foo(x, y):
    # do something at position (x, y)

def foo(pos):
    foo(pos.x, pos.y)

所以我想根据我提供的参数数量调用不同版本的 foo.这当然不起作用,因为我重新定义了 foo.

So I want to call a different version of foo depending on the number of parameters I provide. This of course doesn't work because I redefined foo.

实现这一目标最优雅的方式是什么?我不想使用命名参数.

What would be the most elegant way of achieving this? I would prefer not to use named parameters.

推荐答案

通常您要么定义两个不同的函数,要么执行以下操作:

Usually you'd either define two different functions, or do something like:

def foo(x, y = None):
    if y is None:
        x, y = x.x, x.y
    # do something at position (x, y)

如果您习惯了具有重载的语言,那么定义两个不同函数的选项似乎很笨拙,但如果您习惯了 Python 或 C 等没有重载的语言,那么这就是您所做的.上述代码在 Python 中的主要问题是记录第一个参数有点尴尬,这两种情况并不相同.

The option to define two different functions seems unwieldy if you're used to languages that have overloading, but if you're used to languages like Python or C that don't, then it's just what you do. The main problem with the above code in Python is that it's a bit awkward to document the first parameter, it doesn't mean the same in the two cases.

另一种选择是定义采用 pos 的 foo 版本,但也为用户提供类型:

Another option is to only define the version of foo that takes a pos, but also supply a type for users:

Pos = collections.namedtuple('Pos', 'x y')

那么任何会写 foo(x,y) 的人都可以改写 foo(Pos(x,y)).自然会有轻微的性能成本,因为必须创建一个对象.

Then anyone who would have written foo(x,y) can instead write foo(Pos(x,y)). Naturally there's a slight performance cost, since an object has to be created.

这篇关于“超载"的最佳方式python中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆