重载波浪运算符? [英] Overloading the tilde operator?

查看:52
本文介绍了重载波浪运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重载__invert__运算符(〜),这样它可以接受第二个参数,而不是

self,所以我可以表达:<
x~y


使用:


def __invert __(self,other):<做某事>


例如。这可能吗?


提前致谢,

I am trying to overload the __invert__ operator (~) such that
it can take a second argument, other than
self, so that I can express:

x ~ y

by using:

def __invert__(self, other): <do something>

for example. Is this possible?

Thanks in advance,

推荐答案

Chris写道:
Chris wrote:

我试图重载__invert__运算符(〜)这样

它可以采取第二个参数,而不是

self,所以我可以表达:


x~y


使用:


def __invert __(自我,其他):<做某事>


例如。这可能吗?
I am trying to overload the __invert__ operator (~) such that
it can take a second argument, other than
self, so that I can express:

x ~ y

by using:

def __invert__(self, other): <do something>

for example. Is this possible?



不,在python甚至查找名称之前你会得到一个语法错误:

No, you will get a syntax error before python even look up the names:


>> x
>>x



Traceback(最近一次调用最后一次) :

文件"< stdin>",第1行,在?

NameError:name''x''未定义

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ''x'' is not defined


>> x~x
>>x ~ x



文件"< stdin>",第1行

x~x

^

语法错误:语法无效


彼得

File "<stdin>", line 1
x ~ x
^
SyntaxError: invalid syntax

Peter


Peter Otten:
Peter Otten:

不,你会的在python之前获取语法错误甚至查找名称:
No, you will get a syntax error before python even look up the names:



有些技巧允许使用unde罚款"

Python中的符号,但它们可能只是玩具。我最近在食谱中贴了一个

食谱。


再见,

熊宝宝


Peter Otten写道:
Peter Otten wrote:

Chris写道:

Chris wrote:


>>我正在尝试重载__invert__运算符(〜),这样它可以采取第二个参数,而不是
self,以便我可以表达:

x~y

使用:

def __invert __(self,other):<做某事>

例如。这可能吗?
>>I am trying to overload the __invert__ operator (~) such that
it can take a second argument, other than
self, so that I can express:

x ~ y

by using:

def __invert__(self, other): <do something>

for example. Is this possible?




不,在python甚至查找名称之前你会得到一个语法错误:



No, you will get a syntax error before python even look up the names:


>>>> x
>>>>x



Traceback(最近一次调用最后一次) :

文件"< stdin>",第1行,在?

NameError:名称''x'未定义


Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ''x'' is not defined


>>>> x~x
>>>>x ~ x



文件" ;< stdin>",第1行

x~x

^

语法错误:语法无效


Peter


File "<stdin>", line 1
x ~ x
^
SyntaxError: invalid syntax

Peter



似乎是一个任意限制。考虑


- x




x - y


这与限制一元行动是不一致的。


詹姆斯

Seems an arbitrary limitation. Consider

- x

and

x - y

Which is inconsistent with limiting ~ to a unary operation.

James


这篇关于重载波浪运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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