码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-11 17:39:55      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:color   扩展   tcl   init   people   like   执行   方法   私有属性   

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 类的方法总结

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

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

标签:color   扩展   tcl   init   people   like   执行   方法   私有属性   

原文地址:http://blog.51cto.com/13542406/2059858

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!