Overload * operator in python (or emulate it)

2019-04-12 05:53发布

问题:

I want to overload the * operator in python. In C++, you can overload the dereference operator, so that you can create a class with a custom way to respond to *alpha.

Part of this question is that I don't know exactly, and I mean EXACTLY, what the * operator (unpacking operator as I call it) does.

So how can I overload it, or emulate the overloading of it.

Eventually I want to be able to do: *alpha with a custom response and return value.


EDIT:

I found the solution thanks to Joe Kington's comment. As *alpha unpacks according to __iter__, so I defined a simple class that can be inherited from to allow this.

BTW, the reason I want to be able to do this is because I wanted a pretty interface.

class Deref:
  def __deref__(self):
    pass

  def __iter__(self):
    yield self.__deref__()

class DerefTest(Deref):
  def __deref__(self):
    return '123cat'

if __name__ == '__main__':
  print(*DerefTest()) # prints '123cat'

Eventually I just settled on using another unary operator because the implementation I gave doesn't work in all cases, so I am dissapoint.

回答1:

I don't think you understood the unary * and ** "operators" correctly.

They unpack a list/dict into function arguments/keyword arguments. There is nothing else that makes sense in this context. Thus, they cannot be overloaded.

Actually, using them is a syntax error anywhere but in a function declaration/call.



回答2:

You mean

class Pointer(object):
    def __init__(self, pointee):
        self.pointee = pointee

    def deref(self):
        return self.pointee

is not what you want?

Could you be more specific on what the advantage of writing as *ptr is, instead of ptr.deref() defined above?