[Python] I am trying to use tuple unpacking for a custom iterable. The iterable size should be...

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024.

  1. Stack

    Stack Membro Participativo

    Write a python class that gives the expected output Currently gives ValueError

    # Can be modified. (Can even be a function or generator
    class MyClass:
    def __init__(self):
    self.count = 0

    def __iter__(self):
    return self

    def __next__(self):
    self.count += 1
    return self.count

    #Cannot be modified Cannot pass arguments to MyClass constuctor
    x, y = MyClass()
    print(x, y) # Should return 1, 2
    x, y, z = MyClass()
    print(x, y, z) # 1, 2, 3


    Closest workaround is passing argument to the constructor

    class MyClass:
    def init(self, n):
    self.x = range(n)
    def __iter__(self):
    return iter(x)

    #Cannot be modified I want to avoid passing n
    x, y = MyClass(2)
    x, y, z= MyClass(3)


    Slightly better workaround is to use a very large defualt of n and use * in the end of the lhs

    class MyClass:
    def init(self, n=100):
    self.x = range(n)
    def __iter__(self):
    return iter(x)

    x, y, *_ = MyClass()
    x, y, z, *_ = MyClass()

    Continue reading...

Compartilhe esta Página