标签:python python-2-7
我创建了一个Vehicle类,并希望还有一个派生自它的Car类,它调用父构造函数来设置名称和颜色.但是我收到了这个错误:
super() takes at least 1 argument (0 given)
这是我的代码:
class Vehicle:
def __init__(self, name, color):
self.__name = name # __name is private to Vehicle class
self.__color = color
def getColor(self): # getColor() function is accessible to class Car
return self.__color
def setColor(self, color): # setColor is accessible outside the class
self.__color = color
def getName(self): # getName() is accessible outside the class
return self.__name
self.__model = model
def getDescription(self):
return self.getName() + self.__model + " in " + self.getColor() + " color"
class Car(Vehicle):
def __init__(self, name, color, model):
# call parent constructor to set name and color
super().__init__(name, color)
self.__model = model
def getDescription(self):
return self.getName() + self.__model + " in " + self.getColor() + " color"
# in method getDescrition we are able to call getName(), getColor() because they are
# accessible to child class through inheritance
c = Car("Ford Mustang", "red", "GT350")
print(c.getDescription())
解决方法:
Python 3 – 很好
在Python 3中,这适用于:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
打印:
Vehicle __init__() called
Python 2 – 更多工作
在Python 2中尝试相同的事情会导致问题:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
引发此异常:
Traceback (most recent call last):
...
TypeError: super() takes at least 1 argument (0 given)
我们需要提供自己的类作为第一个,并将自己作为第二个参数提供给super():
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
但这还不够:
Traceback (most recent call last):
...
TypeError: must be type, not classobj
class Vehicle:创建一个旧式的类. Vehicle必须从object继承以获得一个与super()一起使用的新式类:
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
打印:
Vehicle __init__() called
在Python 2中没有参数的super()
必须始终记住这两个论点有点烦人.幸运的是,有一个解决方案.强烈推荐的库Python-Future允许您在Python 2中使用不带参数的super():
from builtins import object, super # from Python-Future
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
打印:
Vehicle __init__() called
标签:python,python-2-7 来源: https://codeday.me/bug/20190829/1761178.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。