开发者

Class Inheritance With Parameters That Have Defaults

开发者 https://www.devze.com 2022-12-18 00:40 出处:网络
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)
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

精彩评论

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

关注公众号