Python 类继承


Python 类继承

#!/usr/bin/python

class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent 方法'

   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 方法'

c = Child()          # instance of child
c.childMethod()      # child calls its 方法
c.parentMethod()     # calls parent's 方法
c.setAttr(200)       # again call parent's 方法
c.getAttr()          # again call parent's 方法