TypeError: object.__init__() takes no parameters异常报错分析

class Car():
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=40
    def get_description_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 ElectirCar():    #定义子类时,括号内必须包含父类的名称
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
my_tesla=ElectirCar('tesla','models',2016)
print(my_tesla.get_description_name())

在新手写python代码时,经常遇到如下的报错:

Traceback (most recent call last):
  File "E:/untitled/random_walk.py", line 23, in 
    my_tesla=ElectirCar('tesla','models',2016)
  File "E:/untitled/random_walk.py", line 22, in __init__
    super().__init__(make,model,year)
TypeError: object.__init__() takes no parameters

发生该类错误的情况有很多,总结一下经常遇到的有以下三种,可以一一排查:

  1. __init__(self,p1,p2)写成了_init_(self,p1,p2)
  2. __init__(self,p1,p2)写成了__int__(self,p1,p2)
  3. 在子类继承代码中缺少了父类的名称,比如如上的代码应该写成下面这样才是正确的:
    class ElectirCar(Car):
        def __init__(self,make,model,year):
            super().__init__(make,model,year)

     

你可能感兴趣的:(Python开发)