开发者

Class Inheritance With Parameters That Have Defaults

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):
        ....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜