2016-08-21 10 views
1

次のコードでは、15分以上再確認しましたが、同じエラーが発生しました。コードは以下のように示されているTypeError:super()は少なくとも1つの引数をとります[Python 3]

TypeError: super() takes at least 1 argument (0 given)

class Car(): 
"""A simple attempt to represent a car.""" 

def __init__(self, make, model, year): 
    self.make = make 
    self.model = model 
    self.year = year 
    self.odometer_reading = 0 

def get_descriptive_name(self): 
    long_name = str(self.year) + ' ' + self.make + ' ' + self.model 
    return long_name.title() 

def read_odometer(self): 
    print("This car has " + str(self.odometer_reading) + " miles on it.") 

def update_odometer(self, mileage): 
    if mileage >= self.odometer_reading: 
     self.odometer_reading = mileage 
    else: 
     print("You can't roll back an odometer!") 

def increment_odometer(self, miles): 
    self.odometer_reading += miles 

class ElectricCar(Car): 
    """Represent aspects of a car, specific to electric vehicles.""" 

    def __init__(self, make, model, year): 
     """Initialize attributes of the parent class.""" 
     super().__init__(make, model, year) 

my_tesla = ElectricCar('tesla', 'model s', 2016) 
print(my_tesla.get_descriptive_name()) 
+1

カークラスの字下げを修正してください –

+2

実際にPython 3ではなくPython 2が使用されていることを確認できますか?「python」を実行している多くのシステムではpython2を取得しています。 'super'はPython 2.7と3.xでは異なっています –

+1

実際、python3の代わりにpython2を使用すると、エラーメッセージ' super() 'が生成されます。 –

答えて

2

ここでの問題は、StackOverflowの上でかなりwell documented 1であるあなたの情報のために、私は崇高なテキストやエラーでそれを実行しました。しかし、どうすればsuper()を間違って使用しているか説明します。 super()を使用しようとしているうちに、Old Style classesという名前のものを使用しています。 新しいスタイルクラスobjectから継承し、で使用できます。Python 2.2以降(Python 3は新しいスタイルのクラスを専有しています)。

あなたCarクラス宣言は次のようになります - あなたのsuper呼び出しは、オブジェクトがであるクラスを持つ、>class Car(object):(ビルトインobjectからCar継承)、および引数として渡されたself

super(ElectricCar, self).__init__(make, model, year) 

、我々はオブジェクトmy_teslaの種類からを印刷場合です:

>>> print type(my_tesla) 
<class '__main__.ElectricCar'>  

これは、タイプがElectricCarであることがわかります。

なぜこのすべてが重要なのですか?まあ、スタイル間にはいくつかの重要な違いがあります。 Oldスタイルでは、インスタンス化のために定義するクラスとオブジェクトは、の異なるタイプです。 Oldスタイルのクラスでは、インスタンスはクラスに関係なく常にタイプinstanceです。新しいスタイルクラスでは、インスタンスは通常、そのクラスが持つのと同じ型を共有します。例:

古いスタイル - >

>>> class MyClass: 
    pass 
>>> print type(MyClass) 
>>> print type(MyClass()) 
<type 'classobj'> 
<type 'instance'> 

新しいスタイル - >

>>> class MyClass(object): 
    pass 
>>> print type(MyClass) 
>>> print type(MyClass()) 
<type 'type'> 
<class '__main__.MyClass'> 

super()上のPythonの公式ドキュメントを参照してください。