栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在元类上拦截运算符查找

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在元类上拦截运算符查找

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

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611109.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号