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.

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?

4
  • Do you mean def __new__(cls, x, y=1):? Commented Jan 27, 2010 at 5:57
  • That's exactly what I meant ^__^ ! I can't believe I didn't think of trying that... thank you. Commented Jan 27, 2010 at 18:26
  • @KennyTM: Can you make that an answer? Commented Feb 19, 2011 at 22:44
  • Super! Not that it's going to get selected, so it will still show up as "Unanswered" but at least it has an answer now. :) Commented Feb 20, 2011 at 11:20

1 Answer 1

4

Put the default parameter on __new__.

class test(int):
    def __new__(cls, x, y=1):
        ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.