如何在 Python 中使用方法重载? [英] How do I use method overloading in Python?

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

问题描述

我正在尝试在 Python 中实现方法重载:

I am trying to implement method overloading in Python:

class A:
    def stackoverflow(self):    
        print 'first method'
    def stackoverflow(self, i):
        print 'second method', i

ob=A()
ob.stackoverflow(2)

但输出是第二种方法2;同样:

class A:
    def stackoverflow(self):    
        print 'first method'
    def stackoverflow(self, i):
        print 'second method', i

ob=A()
ob.stackoverflow()

给予

Traceback (most recent call last):
  File "my.py", line 9, in <module>
    ob.stackoverflow()
TypeError: stackoverflow() takes exactly 2 arguments (1 given)

我该如何完成这项工作?

How do I make this work?

推荐答案

是方法overloading,而不是方法overriding.而在 Python 中,您可以在一个函数中完成所有操作:

It's method overloading, not method overriding. And in Python, you do it all in one function:

class A:

    def stackoverflow(self, i='some_default_value'):
        print 'only method'

ob=A()
ob.stackoverflow(2)
ob.stackoverflow()

在 Python 中你不能有两个同名的方法——你也不需要.

You can't have two methods with the same name in Python -- and you don't need to.

请参阅 Python 教程的默认参数值部分.请参阅最不惊讶"以及要避免的常见错误的可变默认参数.

See the Default Argument Values section of the Python tutorial. See "Least Astonishment" and the Mutable Default Argument for a common mistake to avoid.

请参阅 PEP 443 以了解有关Python 3.4.

See PEP 443 for information about the new single dispatch generic functions in Python 3.4.

这篇关于如何在 Python 中使用方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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