python类继承中构造子的调用
阅读原文时间:2023年07月08日阅读:3

python面向对象中的继承关系中,子类对父类的构造方法的调用有两种方法:

父类名.__init__(self,参数)    #注意名字是父类
super(本子类名,self)__init__(其他参数)    #注意名字是本身子类,而且init后是self之外的参 

例子程序代码:

# -*- coding:utf-8 -*-
class Person(object):

    __metaclass__=type

    def __init__(self,name="Jim"):
        "父类的构造方法,包含初始化属性name"
        self.name=name
        self.flag=False
        print "Person",self.name

    def call(self):
        print self.flag,"name:",self.name
        self.flag = not self.flag

class Programmer(Person):
    __metaclass__=type
    def __init__(self):
        "子类的构造方法,调用父类的构造方法,初始化属性flag"
        #调用方式1
        Person.__init__(self,"DOTJAR")
        print "Programmer"

    def setName(self,name="prgrmr"):
        self.name=name

class Athlete(Person):
    __metaclass__=type
    def __init__(self,name="PaoZhu"):
        "子类的构造方法,调用父类的构造方法,初始化属性flag"
        #调用方式2 注意无参
        super(Athlete,self).__init__(name)
        print "Athlete"

    def setName(self,name="athlete"):
        self.name=name

coder=Programmer()
coder.call()
coder.setName("dotjar")
coder.call()

print("----------------")
athlete=Athlete()
athlete.call()
athlete.setName("LiuXiang")
athlete.call()

输出为:

Person DOTJAR
Programmer
False name: DOTJAR
True name: dotjar

Person PaoZhu
Athlete
False name: PaoZhu
True name: LiuXiang