0

There is a simple class to create a representation of a polynomial (args are ints here):

class MyPolynomial:

    def __init__(self, *args):
        self.numbers = [x for x in args]

I want to create a method able to create a new polynomial, but the argument is a list, so it would work like this:

MyPolynomial.from_iterable([0, 1, 2]) == MyPolynomial(0, 1, 2)

How do I handle a list to pass it as int arguments?

adam_s
  • 43
  • 5
  • Does this answer your question? [How to extract parameters from a list and pass them to a function call](https://stackoverflow.com/questions/7527849/how-to-extract-parameters-from-a-list-and-pass-them-to-a-function-call) – Tomerikoo Dec 07 '20 at 16:49

1 Answers1

1

You can do this:

class MyPolynomial:

    def __init__(self, *args):
        self.numbers = [x for x in args]

    @classmethod
    def from_iterable(cls, the_list):
        # return instance of this class
        return cls(*the_list)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Nice! I'd also just do `self.numbers = list(args)` instead of a no-op list-comp. – tzaman Dec 07 '20 at 16:46
  • Thank you @ForceBru, it looks okay to me and is working, but how do I make it pass a test like this? assert MyPolynomial.from_iterable([0, 1, 2]) == MyPolynomial(0, 1, 2) – adam_s Dec 07 '20 at 18:33
  • @adam_s, this is a completely different question: instances of user-defined classes will compare as non-equal by default. To introduce a notion of equality you'll need to define the `__eq__` magic method, probably like: `def __eq__(self, other): return self.numbers == other.numbers`. – ForceBru Dec 07 '20 at 18:36