www.zhblog.net

__getattr__委托者模式实现

1.调用属性会从__getattr__中获取

2.调用不存在的方法,也会从__getattr__中搜索,返回一个方法注意参数问题


class Delegator(object):
    def __init__(self, delegate):
        self.delegate = delegate

    def __getattr__(self, name):
        attr = getattr(self.delegate, name)

        if not callable(attr):
            return attr

        def wrapper(*args, **kwargs):
            return attr(*args, **kwargs)
        return wrapper


class Delegate(object):
    def __init__(self):
        self.p1 = 123
    
    def do_something(self, something):
        return "Doing %s" % something

 """    
 >>> delegator = Delegator(Delegate())    
 >>> delegator.p1    
 123    
 >>> delegator.p2    
 Traceback (most recent call last):    
 ...    
 AttributeError: 'Delegate' object has no attribute 'p2'    
 >>> delegator.do_something("nothing")    
 'Doing nothing'    
 >>> delegator.do_anything()    
 Traceback (most recent call last):    
 ...    
 AttributeError: 'Delegate' object has no attribute 'do_anything'   
 """    


测试:

>>> def t(*args, **kwargs):
	print('t...', args, kwargs)

>>> class A:
	def __init_(self):
		self.name = 'A'
	def __getattr__(self, name):
		print(name)
		def wrapper(*args, **kwargs):
			return t(*args, **kwargs)
		return wrapper
	def do(self, val):
		print(val)

		
>>> ta = A()
>>> ta.t()
t
t... () {}
>>> ta.t(123)
t
t... (123,) {}
>>> ta.t(123, 456, 'abc', name='t...')
t
t... (123, 456, 'abc') {'name': 't...'}
>>> ta.t
t
<function A.__getattr__.<locals>.wrapper at 0x0000019D97863D90>
>>> ta.b
b
<function A.__getattr__.<locals>.wrapper at 0x0000019D97880268>
>>> ta.b()
b
t... () {}
>>> ta.do
<bound method A.do of <__main__.A object at 0x0000019D97867E48>>
>>> ta.do(1)
1 

 

 

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情