[英]Can I define a “not” operator in Python?
I am trying to interface a C++ library that implements logical operators &&, ||, ! 我试图连接实现逻辑运算符&&,||,!的C ++库。 (unary operator not) to operate on custom selection classes.
(不可使用一元运算符)对自定义选择类别进行操作。
I'm a bit stuck because I can't find an unary 'not' operator in Python. 我有点卡住了,因为在Python中找不到一元的'not'运算符。 Is it possible to override the built in ' not ' operator which works on boolean in Python ?
是否有可能重写在Python中对布尔值起作用的内置' not '运算符?
Is there another suitable operator, or do I need to define a function 'Not()' to implement this behavior? 是否有另一个合适的运算符,还是我需要定义一个函数“ Not()”来实现此行为?
You cannot override the boolean operators ( and
, or
, and not
) with special method hooks, because and
and or
operate lazily and a special method would require that you evaluate operands early instead. 您不能使用特殊的方法钩子覆盖布尔运算符(
and
, or
,和not
),因为and
和or
懒惰地进行操作,而特殊的方法将要求您尽早评估操作数。
You can only influence how the object is evaluated to a boolean (using the __nonzero__
or __len__
methods, depending on whether you are implementing a numeric or container type; Python 3 renamed __nonzero__
to __bool__
). 您只能影响如何将对象评估为布尔值(使用
__nonzero__
或__len__
方法,具体取决于您要实现的是数字类型还是容器类型; Python 3将__nonzero__
重__nonzero__
为__bool__
)。
You can hook into bitwise operators ( &
, |
and ~
), with the __and__
, __or__
, and __invert__
methods, however. 您可以挂接到位运算符(
&
, |
和~
与) __and__
, __or__
和__invert__
但是方法。 This is probably what you are looking for instead. 这可能是您要寻找的。 For
&
and |
对于
&
和|
there are also inverse and in-place hooks available ( __rand__
, __ror__
, __iand__
and __ior__
). 也有反钩和就地钩子(
__rand__
__ror__
, __iand__
__ior__
__ror__
, __iand__
和__ior__
)。
The result of the boolean hooks ( __nonzero__
, etc.) are cast to a boolean ( True
or False
), but the bitwise operator hooks can return anything you like. 布尔值挂钩(
__nonzero__
等)的结果__nonzero__
转换为布尔值( True
或False
),但是按位运算符挂钩可以返回任何您喜欢的值。 ~custom_obj
will evaluate to whatever type(custom_obj).__invert__(custom_obj)
returns; ~custom_obj
将计算为任何type(custom_obj).__invert__(custom_obj)
返回; custom_obj1 & custom_obj2
will return the result of type(custom_obj1).__and__(custom_obj1, custom_obj2)
, unless that method doesn't exist or returns NotImplemented
, in which case type(custom_obj2).__rand__(custom_obj2, custom_obj1)
is called instead. custom_obj1 & custom_obj2
将返回type(custom_obj1).__and__(custom_obj1, custom_obj2)
,除非该方法不存在或返回NotImplemented
,在这种情况下type(custom_obj2).__rand__(custom_obj2, custom_obj1)
将调用type(custom_obj2).__rand__(custom_obj2, custom_obj1)
。
not
just acts on boolean values in python. not
只是作用于Python的布尔值。 If that is sufficient in your use case you can override the __nonzero__
method . 如果这足以满足您的用例,则可以重写
__nonzero__
方法 。 Otherwise your stuck to implement your own obj.inverted()
method. 否则,您将难以实现自己的
obj.inverted()
方法。
>>> hex(~0xaa & 0xff)
'0x55'
Just have to use the matching Python operator. 只需使用匹配的Python运算符即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.