01月11日 四周四次【Python基础进阶】

3.1/3.2 类的继承
3.3 类的属性总结
3.4 类的方法总结

3.1/3.2 类的继承

类的继承
  • 继承是面向对象的重要特点之一
  • 继承关系: 继承是相对两个类而言的父子关系,子类继承父类所有的公有属性和方法
  • 继承实现代码重用
    使用继承
  • 继承可以重用已经存在的数据和行为,减少代码的重复编写.Python在类名后使用一对括号来表示继承关系,括号中的类即为父类
  • class Myclass(ParentClass)
    • 如果父类定义了int方法,子类必须显示调用父类的init方法
      • ParentClass.init(self,[args...])
    • 如果子类需要扩展父类的行为,可以添加init方法的参数
      class People (object):
      color = 'yellow'
      def __init__(self, c):
      print("Init...")
      self.dwell = 'Earth'
      def think(self):
      print("I am a %s"%self.color)
      print("I am a thinker")
      class Chinese(People):
      def __init__(self):
      People.__init__(self,'red')
      pass
      cn = Chinese()
      print(cn.color)
      print(cn.dwell)
      cn.think()
      super函数
      class A(Object):
      def __init__(self):
      print ("enterA")
      print ("leaveA")
      class B(A):
      def __init__(self):
      print ("enetrB")
      super(B,self).__init__()
      print ("leaveB")
      b =  B()
      ###############
      class People (object):
      color = 'yellow'
      def __init__(self, c):
      print("Init...")
      self.dwell = 'Earth'
      def think(self):
      print("I am a %s"%self.color)
      print("I am a thinker")
      class Chinese(People):
      def __init__(self):
      super(Chinese, self).__init__('red')
      pass
      cn = Chinese()
      多重继承
  • python支持多重继承, 即一个类可以继承多个父类
  • 语法
    • class class_name(Parent_c1,Parent_c2,...)
  • 注意:
    • 当父类中出现多个自定义的init方法时,多重继承只执行第一个init方法,其他的不执行
      class People (object):
      def __init__(self):
      self.dwell = 'Earth'
      self.color = 'yellow'
      def think(self):
      print("I am a %s"%self.color)
      print("My home is %s"%self.dwell)
      class Martian(object):
      color = 'red'
      def __init__(self):
      self.dwell = 'Martian'
      def talk(self):
      print("I LIKE")
      class Chinese(Martian,People):
      def __init__(self):
      People.__init__(self)
      cn = Chinese()
      cn.think()
      cn.talk()

3.3 类的属性总结

  • 类属性,也是共有属性
  • 类的私有属性
  • 对象的共有属性
  • 对象的私有属性
  • 内置属性
  • 函数的局部变量
  • 全局变量

3.4 类的方法总结

  • 公有方法
  • 私有方法
  • 类方法
  • 静态方法
  • 内置方法

转载于:https://blog.51cto.com/13542406/2059858

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值