Python中的函数重载:丢失 [英] Function overloading in Python: Missing

查看:88
本文介绍了Python中的函数重载:丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这说:

Python中不存在函数重载.

Function overloading is absent in Python.

就我而言,这也是一种面向对象的语言,因此对我来说是一个很大的障碍.最初,我发现无法区分参数类型很困难,但是Python的动态特性使其变得容易(例如,列表,元组,字符串非常相似).

As far as I feel this a big handicap since its also an OO language. Initially I found that unable to differentiate between the argument types was difficult but the dynamic nature of Python made it easy (e.g. list, tuples, strings are much similar).

然而,计算传递的参数数量然后完成工作就像一个过大的杀伤力.

However counting the number of arguments passed and then doing the job is like an overkill.

推荐答案

正如所指出的,具有默认值的关键字参数可能会走很长一段路.

As unwind noted, keyword arguments with default values can go a long way.

我还将指出,我认为,担心很多类型传递给方法的做法与Python的精神背道而驰.在Python中,我认为使用鸭子类型更被接受-询问对象可以做什么,而不是对象可以做什么.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

因此,如果您的方法可以接受字符串或元组,则可以执行以下操作:

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

然后您可以执行以下任一操作:

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

尽管类似的API有时表明存在设计问题.

Although an API like that sometimes indicates a design problem.

这篇关于Python中的函数重载:丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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