[英]Overload * operator in python (or emulate it)
I want to overload the * operator in python. 我想在python中重载*运算符。 In C++, you can overload the dereference operator, so that you can create a class with a custom way to respond to *alpha
. 在C ++中,您可以重新设置取消引用运算符,以便您可以使用自定义方式创建一个响应*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. 最终我希望能够: *alpha
带有自定义响应和返回值的*alpha
。
EDIT: 编辑:
I found the solution thanks to Joe Kington's comment. 感谢Joe Kington的评论,我找到了解决方案。 As *alpha
unpacks according to __iter__
, so I defined a simple class that can be inherited from to allow this. 由于*alpha
根据__iter__
解包,所以我定义了一个可以继承的简单类来允许这个。
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. 最后我只是决定使用另一个一元运算符,因为我给出的实现在所有情况下都不起作用,所以我很失望。
I don't think you understood the unary *
and **
"operators" correctly. 我认为你没有正确理解一元*
和**
“运算符”。
They unpack a list/dict into function arguments/keyword arguments. 他们将list / dict解压缩到函数参数/关键字参数中。 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. 实际上,使用它们是语法错误,但在函数声明/调用中。
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? 你能更具体地说明写作*ptr
的优点是什么,而不是上面定义的ptr.deref()
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.