替代__iadd__不能正常使用+ =运算符 [英] substituting __iadd__ doesn't work as expected for += operator

查看:109
本文介绍了替代__iadd__不能正常使用+ =运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自库(numpy.ndarray)的对象,在其中我已将__iadd__方法替换为自定义方法. 如果我调用object .__ iadd __(x),它会按预期工作.但是,object + = x似乎调用了旧的(未取代的)方法. 我想防止numpy在特定情况下发生溢出,因此我为此创建了一个上下文管理器.这是(仍然很粗糙)的代码:

I have an object from a library (numpy.ndarray), in which I've substituted the __iadd__ method for a custom one. If I call object.__iadd__(x), it works as expected. However, object+=x seems to call the old (unsubstituted) method. I wanted to prevent overflows on numpy from occurring on specific cases, so I created a context manager for that. Here's the (still very crude) code:

class NumpyOverflowPreventer( object ):
inverse_operator= { '__iadd__':'__sub__', '__isub__':'__add__', '__imul__': '__div__', '__idiv__':'__mul__'}
def _operate( self, b, forward_operator ):
    assert type(b) in (int, float)
    reverse_operator= NumpyOverflowPreventer.inverse_operator[forward_operator]
    uro= getattr(self.upper_range, reverse_operator)
    lro= getattr(self.lower_range, reverse_operator)
    afo= self.originals[ forward_operator ]
    overflows= self.matrix > uro( b )
    underflows= self.matrix < lro( b )
    afo( b )
    self.matrix[overflows]= self.upper_range
    self.matrix[underflows]= self.lower_range

def __init__( self, matrix ):
    m= matrix
    assert m.dtype==np.uint8
    self.matrix= m
    self.lower_range= float(0)
    self.upper_range= float(2**8-1)

def __enter__( self ):
    import functools
    self.originals={}
    for op in NumpyOverflowPreventer.inverse_operator.keys():
        self.originals[ op ] = getattr( self.matrix, op )
        setattr( self.matrix, op, functools.partial(self._operate, forward_operator=op))

def __exit__( self, type, value, tb ):
    for op in NumpyOverflowPreventer.inverse_operator.keys():
        setattr( self.matrix, op, self.originals[ op ] )

运行此:

a= np.matrix(255, dtype= np.uint8)
b= np.matrix(255, dtype= np.uint8)
with NumpyOverflowPreventer(a):
    a+=1
with NumpyOverflowPreventer(b):
    b.__iadd__(1)
print a,b

返回此:

[[0]] [[255]]

推荐答案

您看到的问题是没有在实例上查找特殊的内置方法.在matrix类型上查找它们.因此,在实例上替换它们不会导致它们被间接使用.

The issue you are seeing is that the special built-in methods are not looked up on the instance. They are looked up on the matrix type. So replacing them on the instance will not cause them to be used indirectly.

一种实现目标的方法是将NumpyOverflowPreventer封装为要处理的操作...

One way to achieve your goal is to instead make NumpyOverflowPreventer a wrapper for the operations you want to address...

import numpy as np 
import sys

class NumpyOverflowPreventer(object):

    inverse_operator= { 
        '__iadd__': '__sub__', 
        '__isub__': '__add__', 
        '__imul__': '__div__', 
        '__idiv__': '__mul__'
    }

    def __init__(self, matrix):
        m = matrix
        assert m.dtype==np.uint8
        self.matrix = m
        self.lower_range = float(0)
        self.upper_range = float(2**8-1)

    def __iadd__(self, v):
        # dynamic way to get the name "__iadd__"
        self._operate(v, sys._getframe().f_code.co_name)
        return self

    def _operate(self, b, forward_operator):
        assert type(b) in (int, float)
        reverse_operator = self.inverse_operator[forward_operator]
        uro= getattr(self.upper_range, reverse_operator)
        lro= getattr(self.lower_range, reverse_operator)
        afo= getattr(self.matrix, forward_operator)
        overflows= self.matrix > uro( b )
        underflows= self.matrix < lro( b )
        afo( b )
        self.matrix[overflows]= self.upper_range
        self.matrix[underflows]= self.lower_range

我在这里只定义了__iadd__,我敢肯定,您可以通过一些元类/装饰器动作来动态地完成所有操作...但是我保持简单.

I have only defined __iadd__ here, and I am sure you could do all of them dynamically with some metaclass/decorator action...but I am keeping it simple.

用法:

a = np.matrix(255, dtype= np.uint8)
b = np.matrix(255, dtype= np.uint8)

p = NumpyOverflowPreventer(a)
p+=1

p = NumpyOverflowPreventer(b)
p.__iadd__(1)

print a,b
# [[255]] [[255]]

这篇关于替代__iadd__不能正常使用+ =运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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