python中的重载*运算符(或模拟它) [英] Overload * operator in python (or emulate it)

查看:107
本文介绍了python中的重载*运算符(或模拟它)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重载python中的*运算符.在C ++中,您可以重载解引用运算符,以便可以使用自定义方式创建一个类来响应*alpha.

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.

最终我希望能够做到:*alpha具有自定义响应和返回值.

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

由于乔·肯顿(Joe Kington)的评论,我找到了解决方案.由于*alpha根据__iter__解压缩,因此我定义了一个简单的类,可以从该类继承该类.

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.

推荐答案

我认为您不能正确理解一元***运算符".

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.

这篇关于python中的重载*运算符(或模拟它)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆