Change what the *splat and **splatty-splat operators do to my object

前端 未结 2 830
猫巷女王i
猫巷女王i 2020-12-01 14:55

How do you override the result of unpacking syntax *obj and **obj?

For example, can you somehow create an object thing which b

2条回答
  •  时光取名叫无心
    2020-12-01 15:09

    I did succeed in making an object that behaves how I described in my question, but I really had to cheat. So just posting this here for fun, really -

    class Thing:
        def __init__(self):
            self.mode = 'abc'
        def __iter__(self):
            if self.mode == 'abc':
                yield 'a'
                yield 'b'
                yield 'c'
                self.mode = 'def'
            else:
                yield 'd'
                yield 'e'
                yield 'f'
                self.mode = 'abc'
        def __getitem__(self, item):
            return 'I am a potato!!'
        def keys(self):
            return ['hello world']
    

    The iterator protocol is satisfied by a generator object returned from __iter__ (note that a Thing() instance itself is not an iterator, though it is iterable). The mapping protocol is satisfied by the presence of keys() and __getitem__. Yet, in case it wasn't already obvious, you can't call *thing twice in a row and have it unpack a,b,c twice in a row - so it's not really overriding splat like it pretends to be doing.

提交回复
热议问题