Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can Classes Use Assignment Unpacking Similar to Iterable Lists?

I have list myList = [[1, 2], [3, 4], [5, 6]] which I can use assignment unpacking to get list_instance0, list_instance1, list_instance2 = myList

If I have a class:

class myClass():
    def __init__(self, a: int, b: int):
        self.a = a
        self.b = b
    
    def printAB(self):
        return self.a, self.b

Now If I want to assign the list_instance[i] I can do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

classInstance0=myClass(*list_instance0)
classInstance1=myClass(*list_instance1)
classInstance2=myClass(*list_instance2)

If I was to try

subClass0, subClass1, subClass2 = myClass(*list_instance0, *list_instance1, *list_instance2)
# error "myClass" is not iterable: __iter__ method not defined

So I was wondering is there a way to assign classInstance[i] with list_instance[i] to myClass in a more dynamic way instead of having to assign each one individually?

>Solution :

You simply want to map MyClass over your list.

from itertools import starmap

subClass0, subClass1, subClass2 = starmap(myClass, myList)

starmap ensures the contents of each sublist are passed as separate arguments to myClass, rather than the sublist itself passed as a single argument.

or you can use a list comprehension to be a little more explicit:

subClass0, subClass1, subClass2 = [myClass(*x) for x in myList]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading