class father():
def __init__(self,age):
self.age = age
def get_age(self):
print(self.age)
class son(father):
def __init__(self,age):
super().__init__(age)
self.toy_number = 5
def get_toy_number(self):
print(self.toy_number)
myson = son(6)
myson.get_age()
myson.get_toy_number()
运行时报错:“TypeError: super() takes at least 1 argument(0 given)”
上述继承方法super()的调用是python3中的方法,而运行环境是在python2中进行的,所以会存在不兼容的情况出现。
如果要在python2的环境中运行,那么需要将参考《python编程:从入门到实践》:
super().__init__(age)
改为:
super(son,self).__init__(age)
改完以后,运行时报错:
“TypeError: super() argument 1 must be type, not classobj”
上述方法行不通,需要进行以下的更改:
class father(object): #这里添加object
def __init__(self,age):
self.age = age
def get_age(self):
print(self.age)
class son(father):
def __init__(self,age):
super(son, self).__init__(age) #这里改为super(son,self).__init__(age)
self.toy_number = 5
def get_toy_number(self):
print(self.toy_number)
myson = son(6)
myson.get_age()
myson.get_toy_number()
class father():
def __init__(self,age):
self.age = age
def get_age(self):
print(self.age)
class son(father):
def __init__(self,age):
father.__init__(self,age) #此处的参数含self
self.toy_number = 5
def get_toy_number(self):
print(self.toy_number)
myson = son(6)
myson.get_age()
myson.get_toy_number()
参考