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.__n开发者_JS百科ew__(cls, x+y)
test(2,3)#Is equal to 5
test(2)#Should equal 3 but __new__ (and other defs) ignore y=1.
I know you can do this with a normal function, but it is just an example. However, I need to inherit from a class and I don't like using *args (unless you can convince me to like them..). So how can I get y to default to some value?
Put the default parameter on __new__
.
class test(int):
def __new__(cls, x, y=1):
....
精彩评论