编程模式-委托
委托属性的访问:
对当前类属性方法等的访问委托到其内部对象上,可以作为继承的一种替代方案
1 class ProtoType: 2 def __init__(self): 3 self.name = "g" 4 5 def func(self): 6 print(self.name) 7 8 9 class Valley: 10 def __init__(self): 11 self.delegate = ProtoType() 12 13 def __getattr__(self, item): 14 """访问当前类实例并不存在的属性时会自动触发""" 15 return getattr(self.delegate, item) 16 17 18 if __name__ == '__main__': 19 Valley().func()
浙公网安备 33010602011771号