python面向对象中的继承关系中,子类对父类的构造方法的调用有两种方法:
1. 父类名.init(self,参数)
2. super(本子类名,self)init(其他参数)
父类名.__init__(self,参数) #注意名字是父类
super(本子类名,self)__init__(其他参数) #注意名字是本身子类,而且init后是self之外的参
3. 示例代码:
# -*- 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 True name: LiuXiang
---[2012\-07\-17]---
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 hi@niewj.com