我是 Python 语言的新手。我只有10天的经验。当我开始学习时没有什么困难,但是当我到达“面向对象的概念”,尤其是“继承”时,它让我放慢了速度。
我的一些背景知识“继承是子类可以获得父类的所有特征和行为,换句话说 - 父类的数据和方法”。好的,我将展示使我与两个程序混淆的概念。他们都得到了相同的结果,所以为什么人们会做出不同的事情。
第一的:
class Parent():
parentdata = 0
def __init__(self):
pass
def getParentData(self):
return Parent.parentdata
def setParentData(self, setdata):
Parent.parentdata = setdata
class Child(Parent):
childdata = 0
def __init__(self):
pass
def getChildData(self):
return Child.childdata
def setChildData(self, setdata):
Child.childdata = setdata
child = Child()
print "Default Child's Data is :" + str(child.getChildData())#getting 0
child.setChildData(3)
print "After Adding Child's Data is :"+ str(child.getChildData()) # getting 3
print "Default Parent's Data is:"+ str(child.getParentData())# getting 0
child.setParentData(1)
print "After Adding Parent's Data is :"+str(child.getParentData())# getting 1
第二:
class Parent():
parentdata = 0
def __init__(self):
pass
def getParentData(self):
return Parent.parentdata
def setParentData(self, setdata):
Parent.parentdata = setdata
class Child(Parent):
childdata = 0
def __init__(self):
#super(Child, self).__init__()
#super(Child, self).__init__(self, self)
Parent.__init__(self)
def getChildData(self):
return Child.childdata
def setChildData(self, setdata):
Child.childdata = setdata
child = Child()
print "Default Child's Data is :" + str(child.getChildData())#getting 0
child.setChildData(3)
print "After Adding Child's Data is :"+ str(child.getChildData()) # getting 3
print "Default Parent's Data is:"+ str(child.getParentData())# getting 0
child.setParentData(1)
print "After Adding Parent's Data is :"+str(child.getParentData())# getting 1
也请指导我,如何使用Super()
方法,例如Parent.__init__(self)
Somebody used, Super method in there 和 some are doing as my way。我不清楚这两种不同。
在这两个程序中 - 我没有__init__
用作构造函数。如果我要使用__init__
as 将数据添加到类的数据(子数据,父数据)中,我如何在Parent.__init__(self)
它们的def __init__(self):
方法中插入参数?