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!

2
  • 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, ...)? Commented Nov 26, 2022 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. Commented Nov 26, 2022 at 19:22

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Iterable is a generic, so it should have a type parameter, shouldn't it? I think Iterable[object] would be appropriate.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.