adam_s
adam_s

Reputation: 43

Passing list as an argument to a class

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?

Upvotes: 0

Views: 43

Answers (1)

ForceBru
ForceBru

Reputation: 44838

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)

Upvotes: 1

Related Questions