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  
<class '__main__.Programmer'>  
\----------------  
Person PaoZhu  
Athlete  
False name: PaoZhu  

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Scroll Up