1

I made a class which looks something like.

class NewInt:
  def __init__(self, x,y):
    self.holders = {"x":x,"y":y}

Now, I have a number say a dictionary. So everything is exactly same

except its not NewInt but a dict.Somethng like

 A  {"x": 3,"y":4}

So it is exactly of type NewInt except its a dictionary.

Is there a way i can do something like

this_int = NewInt(A)

I forgot but there was a special name to such constructor where assignment is done ?? Thanks

2
  • 1
    I don't quite understand you... Try this_int = NewInt(**A). Commented Apr 6, 2012 at 22:07
  • 1
    For more general cases, you might want to watch PEP 3124 which would introduce overloading to python, making it easier to make constructors that vary based on input. Commented Apr 6, 2012 at 22:13

1 Answer 1

4

You can use keyword arguments:

A = {"x": 3,"y":4}
this_int = NewInt(**A)

By the way, it's looking like you're reimplementing complex numbers. Those are already built in to Python, try complex(3,4) or 3+4j.

Sign up to request clarification or add additional context in comments.

1 Comment

You may need to add an additional **kwargs argument for this to work when the dictionary has extra keywords, otherwise you'll get a TypeError for the unexpected extra keyword argument(s).

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.