python_类的一些方法

代码:

class Super:
    def delegate(self):
        self.action()
        
class Provider(Super):
    def action(self):
        print 'in Provider.action'
        
x = Provider()
x.delegate()

结果:

in Provider.action

在Super类中定义delegate()方法,delegate中调用self.action,在Provider子类中实现action方法。子类调用父类的delegate方法时,实际是调用自己的action方法。。

一句话:

子类实现了父类delegate中所期望的action方法


代码:

class Super:
    def delegate(self):
        self.action()
    def method(self):
        print 'super method'
    
class Inherit(Super):
    pass

class Replace(Super):
    def method(self):
        print "replace method"
        
class Extended(Super):
    def method(self):
        print 'in extended class'
        Super.method(self)
        print 'out extended class'
    
class Provider(Super):
    def action(self):
        print 'in Provider.action'
        
x = Inherit()
x.method()
print '*'*50

y = Replace()
y.method()
print '*'*50

z = Extended()
z.method()
print '*'*50

x = Provider()
x.delegate()

结果:

super method
**************************************************
replace method
**************************************************
in extended class
super method
out extended class
**************************************************
in Provider.action

分别继承父类的方法,替换父类的方法,扩展了父类的方法

Super类定义了delegate方法并期待子类实现action函数,Provider子类实现了action方法.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值