Python 中的类和继承简介

pythonserver side programmingprogramming

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

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

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

由于 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 attribute :", 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

输出

When the above code is executed, it produces the following result 

Calling child constructor
Calling child method
Calling parent method
Parent attribute :200
 

相关文章


有用资源