类继承在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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短