Python中的类和继承简介

面向对象的编程创建可重用的代码模式,以防止项目中的代码冗余。创建可回收代码的一种方法是通过继承,即一个子类利用另一基类的代码。

继承是指一个类使用另一个类中编写的代码。

称为子类或子类的类从父类或基类继承方法和变量。

因为Child子类是从Parent基类继承的,所以Child类可以重用Parent的代码,从而允许程序员使用更少的代码行并减少冗余。

派生类的声明与父类很相似;但是,在类名称后给出了要继承的基类列表-

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

示例

class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"
   def parentMethod(self):
      print 'Calling parent method'
   def setAttr(self, attr):
      Parent.parentAttr = attr
   def getAttr(self):
      print "父级属性:", Parent.parentAttr
class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"
   def childMethod(self):
      print 'Calling child method'
c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

输出结果

执行以上代码后,将产生以下结果 

Calling child constructor
Calling child method
Calling parent method
父级属性:200