如何在Python中使用方法重载? [英] How do I use method overloading in Python?
本文介绍了如何在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)
如何使这项工作?
推荐答案
em>覆盖。在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中使用两个相同名称的方法, to。
You can't have two methods with the same name in Python -- and you don't need to.
See the Default Argument Values section of the Python tutorial. See "Least Astonishment" in Python: The Mutable Default Argument for a common mistake to avoid.
编辑:请参阅 PEP 443 了解有关Python 3.4中新的单一分派通用函数的信息。
Edit: See PEP 443 for information about the new single dispatch generic functions in Python 3.4.
这篇关于如何在Python中使用方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文