加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python中的代理对象

发布时间:2020-12-20 12:07:18 所属栏目:Python 来源:网络整理
导读:我正在寻找方法将方法调用从对象(包装器)传递到对象的成员变量(wrappee).可能有许多方法需要外部化,因此在向wrapee添加方法时,如果不更改包装器的接口,这样做是有帮助的. class Wrapper(object) def __init__(self,wrappee): self.wrappee = wrappee def foo
我正在寻找方法将方法调用从对象(包装器)传递到对象的成员变量(wrappee).可能有许多方法需要外部化,因此在向wrapee添加方法时,如果不更改包装器的接口,这样做是有帮助的.

class Wrapper(object)
  def __init__(self,wrappee):
    self.wrappee = wrappee

  def foo(self):
    return 42

class Wrappee(object):
  def bar(self):
    return 12

o2 = Wrappee()
o1 = Wrapper(o2)

o1.foo() # -> 42
o1.bar() # -> 12
o1.<any new function in Wrappee>() # call directed to this new function

如果这个呼叫重定向是“快速”(相对于直接呼叫,即不增加太多开销),那将是很好的.

解决方法

一个稍微优雅的解决方案是在包装类上创建一个“属性代理”:

class Wrapper(object):
    def __init__(self,wrappee):
        self.wrappee = wrappee

    def foo(self):
        print 'foo'

    def __getattr__(self,attr):
        return getattr(self.wrappee,attr)


class Wrappee(object):
    def bar(self):
        print 'bar'

o2 = Wrappee()
o1 = Wrapper(o2)

o1.foo()
o1.bar()

所有的魔法都发生在Wrapper类的__getattr__方法上,它将尝试访问Wrapper实例上的方法或属性,如果它不存在,它将尝试包装它.

如果您尝试访问任一类上不存在的属性,您将得到:

o2.not_valid
Traceback (most recent call last):
  File "so.py",line 26,in <module>
    o2.not_valid
  File "so.py",line 15,in __getattr__
    raise e
AttributeError: 'Wrappee' object has no attribute 'not_valid'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读