一些黑魔法可以帮助您实现目标:
operators = ["add", "mul"]class OperatorHackiness(object): """ Use this base class if you want your object to intercept __add__, __iadd__, __radd__, __mul__ etc. using __getattr__. __getattr__ will called at most _once_ during the lifetime of the object, as the result is cached! """ def __init__(self): # create a instance-local base class which we can # manipulate to our needs self.__class__ = self.meta = type('tmp', (self.__class__,), {})# add operator methods dynamically, because we are damn lazy.# This loop is however only called once in the whole program# (when the module is loaded)def create_operator(name): def dynamic_operator(self, *args): # call getattr to allow interception # by user func = self.__getattr__(name) # save the result in the temporary # base class to avoid calling getattr twice setattr(self.meta, name, func) # use provided function to calculate result return func(self, *args) return dynamic_operatorfor op in operators: for name in ["__%s__" % op, "__r%s__" % op, "__i%s__" % op]: setattr(OperatorHackiness, name, create_operator(name))# Example user classclass Test(OperatorHackiness): def __init__(self, x): super(Test, self).__init__() self.x = x def __getattr__(self, attr): print "__getattr__(%s)" % attr if attr == "__add__": return lambda a, b: a.x + b.x elif attr == "__iadd__": def iadd(self, other): self.x += other.x return self return iadd elif attr == "__mul__": return lambda a, b: a.x * b.x else: raise AttributeError## Some test pre:a = Test(3)b = Test(4)# let's test additionprint(a + b) # this first call to __add__ will trigger # a __getattr__ callprint(a + b) # this second call will not!# same for multiplicationprint(a * b)print(a * b)# inplace addition (getattr is also only called once)a += ba += bprint(a.x) # yay!
输出量
__getattr__(__add__)77__getattr__(__mul__)1212__getattr__(__iadd__)11
现在,您可以通过继承我的
OperatorHackiness基类来使用第二个代码示例。您甚至可以获得额外的好处:
__getattr__每个实例和每个运算符仅被调用一次,并且缓存不涉及额外的递归层。我们在此规避了方法调用比方法查找慢的问题(正如Paul
Hankin正确注意到的那样)。
注意 :添加运算符方法的循环在整个程序中仅执行一次,因此准备工作在毫秒范围内会产生恒定的开销。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)