ex44——继承与合成

class Parent():
    def override(self):
        print("parent override()")

    def implicit(self):
        print("parent implicit()")

    def altered(self):
        print("parent altered()")


class Child(Parent):
    def override(self):
        print("child override()")

    def altered(self):
        print("child, before parent altered()")
        super().altered()
        print("child, after parent altered()")

dad = Parent()
son = Child()
# 隐式继承,父类定义了implicit函数,但没有在子类中定义,子类会从父类继承所有的行为
dad.implicit()
son.implicit()
# 显示继承,子类override函数有一个不同的行为,从而实现子类的新功能。
dad.override()
son.override()
# 在运行前或运行后替换,在继承父类函数前或后再修改行为。使用python的内置函数super来调用父类里的函数。
dad.altered()
son.altered()

RESULT:
parent implicit()
parent implicit()
parent override()
child override()
parent altered()
child, before parent altered()
parent altered()
child, after parent altered()
  1. 在python2.7中,继承语法稍有不同,Son类定义类似于下面这样:
# 初始化
class Parent(object):
	def __init__(self):
		--snip--
class Son(Parent):
	def __init__(self):
		super(Son,self).__init__()
		--snip--# 无需初始化
class Parent(object):
	def func(self):
		--snip--
class Son(Parent):
	def func(self):
		super(Son,self).func()
		--snip--
  1. 函数super()需要两个实参:子类名和对象self。为帮助Python将父类和子类关联起来,这些实参必不可少,另外,在Python2.7中使用继承是,务必在定义父类是在括号内指定object。

  2. 继承是一种有用的技术,但也可以直接使用别的类和模块实现同样功能。

class Other():
    def override(self):
        print("Other override()")

    def implicit(self):
        print("OTHER implicit()")

    def altered(self):
        print("OTHER altered()")

class Child():
    def __init__(self):
        self.other = Other()

    def implicit(self):
        self.other.implicit()

    def override(self):
        print("CHILD override()")

    def altered(self):
        print("CHILD, before OTHER altered()")
        self.other.altered()
        print("CHILD, after OTHER altered()")

son = Child()
son.implicit()
son.override()
son.altered()

RESULT:
OTHER implicit()
CHILD override()
CHILD, before OTHER altered()
OTHER altered()
CHILD, after OTHER altered()

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值