2
class test(int):
def __init__(self, x, y=1):#y defaults to 1
self.x=x
self.y=y
def __new__(cls, x, y):
return int.__new__(cls, x+y)
test(2,3)#Is equal to 5
test(2)#Should equal 3 but __new__ (and other defs) ignore y=1.
我知道你可以用普通函数做到这一点,但它只是一个例子。然而,我需要从一个类继承,我不喜欢使用*参数(除非你能说服我喜欢他们..)。那么我怎么能让y默认为某个值呢?具有默认参数的类继承
您的意思是'def __new __(cls,x,y = 1):'? – kennytm 2010-01-27 05:57:35
这就是我的意思^ __ ^!我不敢相信我没有想到这么做......谢谢。 – what 2010-01-27 18:26:16
@KennyTM:你能否做出答案? – 2011-02-19 22:44:21