Search code examples
pythonpython-class

How to instantiate object using iterable in Python?


I need to instantiate an object using iterable with multiple objects inside. I have to create another method to do it

class MyClass:

  def __init__(self, *args):
    self.args = args

  def instantiate_from_iterable
     #some clever code

I need to have a result like this

MyClass.instantiate_from_iterable([1, 5, 3]) == MyClass(1, 5, 3)

MyClass.instantiate_from_iterable((3, 1, 7)) == MyClass(3, 1, 7)

I have no idea how to do this. If someone could help, I would appreciate it very much!


Solution

  • classmethod is what what you're after:

    from collections.abc import Iterable
    
    class MyClass:
        def __init__(self, *args):
            self.args = args
       
        @classmethod
        def instantiate_from_iterable(cls, args: Iterable):
            return cls(*args)
    
        
    a = MyClass(1, 5, 7)
    b = MyClass.instantiate_from_iterable([1, 5, 7])
         
    print(a.args)  # -> (1, 5, 7)
    print(b.args)  # -> (1, 5, 7)