这是python函数重载的一个例子吗? [英] Is this an example of python function overload?

查看:59
本文介绍了这是python函数重载的一个例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道python不允许我们重载函数.但是,它有内置的重载方法吗?

I know python does not allow us to overload functions. However, does it have inbuilt overloaded methods?

考虑一下:

setattr(object_name,'variable', 'value')

setattr(class_name,'method','function')

第一个语句在运行时动态地向对象添加变量,但第二个语句在运行时将外部函数附加到类.

The first statement dynamically adds variables to objects during run time, but the second one attaches outside functions to classes at run time.

同一个函数根据它的参数做不同的事情.这个函数重载了吗?

The same function does different things based on its arguments. Is this function overload?

推荐答案

setattr(foo, 'bar', baz) 函数总是与 foo.bar = baz<相同/code>,不管 foo 的类型.这里没有重载.

The function setattr(foo, 'bar', baz) is always the same as foo.bar = baz, regardless of the type of foo. There is no overloading here.

在 Python 3 中,可以使用 functools 进行有限的重载.singledispatch,但是 setattr 没有实现.

In Python 3, limited overloading is possible with functools.singledispatch, but setattr is not implemented with that.

在我看来,一个更有趣的例子是 type().type() 根据你如何称呼它做了两件完全不同的事情:

A far more interesting example, in my opinion, is type(). type() does two entirely different things depending on how you call it:

  1. 如果使用单个参数调用,则返回该参数的类型.
  2. 如果使用三个参数(正确类型)调用,它会动态创建一个新类.

尽管如此,type() 没有重载.为什么不?因为它是作为一个函数实现的,计算它得到了多少个参数 然后决定做什么.在纯 Python 中,这是使用可变参数 *args 语法完成的,但是 type() 是用 C 实现的,因此看起来很不一样.不过,它也在做同样的事情.

Nevertheless, type() is not overloaded. Why not? Because it is implemented as one function that counts how many arguments it got and then decides what to do. In pure Python, this is done with the variadic *args syntax, but type() is implemented in C, so it looks rather different. It's doing the same thing, though.

这篇关于这是python函数重载的一个例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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