在元类上拦截运算符查找

在元类上拦截运算符查找,第1张

在元类上拦截运算符查找

一些黑魔法可以帮助您实现目标:

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正确注意到的那样)。

注意 :添加运算符方法的循环在整个程序中仅执行一次,因此准备工作在毫秒范围内会产生恒定的开销。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5617232.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存