我想为类函数中的类实例定义运算符,如下所示:
class MyClass(object):
@property
def _arithmetic_threshold(self):
return self.threshold # this will be defined somewhere
@_arithmetic_threshold.setter
def _arithmetic_threshold(self,value):
self.threshold = value
self._define_arithmetic_attributes()
def _define_arithmetic_attributes(self):
"""
Wrapper to define all arithmetic attributes (in order to allow threshold changes)
"""
self.__add__ = self._operation_wrapper(np.add,threshold=self._arithmetic_threshold)
self.__sub__ = self._operation_wrapper(np.subtract,threshold=self._arithmetic_threshold)
self.__mul__ = self._operation_wrapper(np.multiply,threshold=self._arithmetic_threshold)
self.__div__ = self._operation_wrapper(np.divide,threshold=self._arithmetic_threshold)
然而,这似乎不起作用-我觉得我遗漏了一些关于操作符-
、+
等如何调用这些函数的信息。i、 电子邮件:
class MyClass2(object):
def __add__(self,other,threshold=None):
if threshold is not None:
return self+other
else:
# do something here involving checking a threshold....
pass
在MyClass2中,__add__
的行为将不同。有谁能解释一下它们的不同之处,以及如何使MyClass中的操作符方法的行为类似于MyClass2?你知道吗
编辑:为了弄清楚我为什么要这么做,这里是_operation_wrapper
。这个类是一个“光谱”对象,它有一个X轴和一个Y轴。目标是允许在Y轴上进行算术运算,但前提是X轴匹配。但是,它们可以匹配到1/5像素大小,所以我想做更多纯粹的“精确”匹配。你知道吗
def _operation_wrapper(operation):
"""
Perform an operation (addition, subtraction, mutiplication, division, etc.)
after checking for shape matching
"""
def ofunc(self, other):
if np.isscalar(other):
newspec = self.copy()
newspec.data = operation(newspec.data, other)
return newspec
else: # purely for readability
if self._arithmetic_threshold == 'exact':
xarrcheck = all(self.xarr == other.xarr)
else:
if self._arithmetic_threshold_units is None:
# not sure this should ever be allowed
xarrcheck = all((self.xarr-other.xarr) < self._arithmetic_threshold)
else:
xarrcheck = all((self.xarr.as_unit(self._arithmetic_threshold_units)-other.xarr.as_unit(self._arithmetic_threshold_units)) < self._arithmetic_threshold)
if self.shape == other.shape and xarrcheck:
newspec = self.copy()
newspec.data = operation(newspec.data, other.data)
return newspec
elif self.shape != other.shape:
raise ValueError("Shape mismatch in data")
elif not xarrcheck:
raise ValueError("X-axes do not match.")
return ofunc
像
__add__()
这样的特殊方法是在对象的类型上查找的,而不是在实例上。所以呢大致翻译为
这意味着在实例上设置
__add__
没有任何用处(除了使a.__add__(b)
工作)。你知道吗你的例子有点不完整,所以我不能提供完整的工作代码。您可以将代码从
_define_arithmetic_attributes()
移动到类主体,并从operation_wrapper()
内部访问self.threshold
。你知道吗(注意,我没有理解
_arithmetic_threshold
属性的要点。为什么不直接访问self.threshold
本身?)你知道吗相关问题 更多 >
编程相关推荐