具有默认值的参数的类继承

时间:2010-01-27 05:39:58

标签: python-3.x

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.

我知道你可以用正常功能做到这一点,但这只是一个例子。但是,我需要继承一个类,我不喜欢使用* args(除非你能说服我喜欢它们)。那么如何让y默认为某个值呢?

1 个答案:

答案 0 :(得分:4)

将默认参数放在__new__

class test(int):
    def __new__(cls, x, y=1):
        ....
相关问题