我试图在Python中实现方法重载:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow(2)
但是输出是second method 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)
我该怎么做?
也可以使用pythonlangutil:
这是方法重载而不是方法重写。在Python中,您可以在一个函数中完成这一切:
在Python中,不能有两个同名的方法,也不需要。
请参阅Python教程的Default Argument Values部分。请参阅"Least Astonishment" and the Mutable Default Argument以了解要避免的常见错误。
编辑:有关Python 3.4中新的单分派泛型函数的信息,请参见PEP 443。
在Python中,你不会那样做。当人们在Java这样的语言中这样做时,他们通常需要一个默认值(如果不需要,他们通常需要一个具有不同名称的方法)。所以,在Python中,you can have default values。
如您所见,您可以使用这个来触发单独的行为,而不仅仅是有一个默认值。
相关问题 更多 >
编程相关推荐