Overload * operator in python (or emulate it)

雨燕双飞 提交于 2019-12-06 08:11:08

问题


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?



来源:https://stackoverflow.com/questions/9722272/overload-operator-in-python-or-emulate-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!