python - Can I create a class which can be unpacked? -
for example:
x = (1, 2) a,b = x
now i'd accomplish in case of x
being instance of class isn't list or tuple. overriding __getitem__
or __getslice__
doesn't work:
class test(object): def __getitem__(self, key): return 1 a,b = test()
results in valueerror: many values unpack
. can make work without inheriting list
or tuple
(or respective userx
classes)? or under-the-hood magic cannot use?
you need override __iter__
or __getitem__
. here's example using __iter__
:
class test(object): def __iter__(self): return iter([1, 2]) a,b = test()
be careful, __iter__
needs return iterator. easiest way either wrap data structure in iter
, or have yield generator.
for example of using __getitem__
, see jonrsharpe's excellent answer.
Comments
Post a Comment