欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python基础第二十一课--OOP委托模式(小白piao分享)

程序员文章站 2022-07-14 18:59:40
...

什么是委托模式?

        委托者模式是指将类的一些属性委托到内部持有的一个对象上,让其完成一些工作的模式。

目的:

        作为继承的替代方案或为了实现一种代理机制。

继承替代的例子:

class Gunner:#抢手为被委托方 ---类似父类
    def dohomework(self,name):
        print(name,'(gunnner) is doing homework ...',sep='')
    def do_exam(self,name):
        print(name,'(gunnner) is examing...',sep='')

class Student:#类似子类
    def __init__(self,name):
        self._gunner = Gunner()
        self.name = name
    def do_homework(self):#雇佣抢手写作业
        self._gunner.dohomework(self.name)
    def do_exam(self):#雇佣抢手考试
        self._gunner.do_exam(self.name)
    def play(self):
        print('I`m playing basketball ...')

小白piao = Student('小白piao')
小白piao.do_exam()
小白piao.do_homework()
小白piao.play()
print(小白piao.__dict__)

#结果:
'''
小白piao(gunnner) is examing...
小白piao(gunnner) is doing homework ...
I`m playing basketball ...
{'_gunner': <__main__.Gunner object at 0x0000025E35B03898>, 'name': '小白piao'}

Process finished with exit code 0
'''

        如果被委托方仅仅只有个别方法被委托,则上述例子足矣,但是如果需要被委托方帮委托方做所有被委托方做的事情的话:一种方法是在委托方类中写上所有的调用被委托方方法的方法。另外一种更加轻松的方式如下:

class Gunner:
    def dohomework(self,name):
        print(name,'(gunnner) is doing homework ...',sep='')
    def do_exam(self,name):
        print(name,'(gunnner) is examing...',sep='')
    def play_soccer(self):
        print('playing ...')

class Student:
    def __init__(self,name):
        self._gunner = Gunner()
        self.name = name
    def do_homework(self):
        self._gunner.dohomework(self.name)
    def do_exam(self):
        self._gunner.do_exam(self.name)
    def play(self):
        print('I`m playing basketball ...')
    def __getattr__(self, item):
        return getattr(self._gunner,item)#得到gunner中名字为item的属性

小白piao = Student('小白piao')
小白piao.play_soccer()
小白piao.do_exam()#这个方法是自己的,和抢手方法同名
小白piao.dohomework('抢手')#这个方法是抢手的

print(小白piao.__getattr__('do_exam'))
#结果:
'''
playing ...
小白piao(gunnner) is examing...
抢手(gunnner) is doing homework ...
<bound method Gunner.do_exam of <__main__.Gunner object at 0x000001ED72CB4908>>
'''

代理机制的例子

class Proxy:
    def __init__(self,obj):
        self._obj = obj
    def __getattr__(self, item):
        return getattr(self._obj,item)
    def __setattr__(self, key, value):
        if key.startswith('_'):
            super(Proxy, self).__setattr__(key,value)
        else:
            setattr(self._obj,key,value)
    def __delete__(self, instance):
        if instance.startswith('_'):
            super(Proxy, self).__delete__(instance)
        else:
            delattr(self._obj,instance)

class Spam:
    def __init__(self,value):
        self.x = value
    def bar(self,value):
        print('bar spam:',self.x,value)

s = Spam(3)
p = Proxy(s)
print(p.x)#3
p.bar(37)#bar spam: 3 37
p.x = 30
p.y = 28
print(s.y)#28
相关标签: python基础