类继承在Python中如何工作?
类的继承
无需重新定义类,我们可以通过在新类名称后的括号中列出父类来从现有类派生该类,从而创建一个类。
子类继承其父类的属性,我们可以使用这些属性,就像它们是在子类中定义的一样。子类也可以覆盖父类的数据成员和方法。
语法
派生类的声明与父类很相似;但是,在类名称后给出了要继承的基类列表-
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
示例
#!/usr/bin/python
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