0

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!

Piotrek
  • 13
  • 3
  • Could you provide an (abstract) example of what the result of such an instantiation would be? So how are the multiple objects inside the outtermost object positioned (nested, ...)? – CodingTil Nov 26 '22 at 18:40
  • Welcome to Stack Overflow! Check out the [tour]. Your question covers the same topics as some existing ones, so I've closed it accordingly, but if there's some subtlety I'm missing, LMK (like for example, `MyClass.__eq__()` is undefined, so I'm assuming it'd be implemented as `self.args == other.args`). For more tips, check out [How to ask a good question](/help/how-to-ask). – wjandrea Nov 26 '22 at 19:22

2 Answers2

3

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • `Iterable` is a generic, so it should have a type parameter, shouldn't it? I think `Iterable[object]` would be appropriate. – wjandrea Nov 26 '22 at 19:01
0

I am not sure what you would like to do.

Try the following:

class MyClass:

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

    
    def __eq__(self, other):
        if not isinstance(other, MyClass):
            return False
        else:
            return self.args == other.args

assert MyClass(1, 5, 3) == MyClass(*[1, 5, 3]) 

There would be no need for a clever function. Just unpack the list with the * before the list or tuple. You would make the object comparably using the magic function __eq__ to make them comparable.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
NameVergessen
  • 598
  • 8
  • 26