Python中的特定类

Python中的特定类,python,Python,我正在写一个计算汽车燃油效率的程序。代码如下: class Car: def __init__(self, fuelEfficiency, fuelLevel): self.fuelEfficiency = fuelEfficiency self.fuelLevel = 0 def drive(self, miles): gasUsed = self.fuelEfficiency * miles self.fue

我正在写一个计算汽车燃油效率的程序。代码如下:

class Car:
    def __init__(self, fuelEfficiency, fuelLevel):
        self.fuelEfficiency = fuelEfficiency
        self.fuelLevel = 0

    def drive(self, miles):
        gasUsed = self.fuelEfficiency * miles

        self.fuelLevel -= gasUsed

        self.fuelLevel = max(self.fuelLevel, 0)

    def get_gas_level(self):
        return self.fuelLevel

    def add_gas(self, gallons):
        self.fuelLevel += gallons

    def __str__(self):
        return ('$.2f gallons remaining.' % (self.fuelLevel))

def main():
    print("Fuel Estimator")

    fuelEfficiency = float(input('MPG: '))
    fuelLevel = float(input('Fuel: '))
    miles = float(input('Distance: '))
    gallonsRemaining = Car(fuelLevel)

    while True:
        x = input("Would you like to enter another (y/n): ")

        if x == "y":
            main()
            continue
        elif x == "n":
            break
        else:
            print("Would you like to enter another (y/n): ")

if __name__ == "__main__":
    main()
以下是错误的回溯:

Traceback (most recent call last):
  File "C:\Users\John\Desktop\prog4.py", line 5, in <module>
    class Car:
  File "C:\Users\John\Desktop\prog4.py", line 47, in Car
    main()
  File "C:\Users\John\Desktop\prog4.py", line 33, in main
    gallonsRemaining = Car(fuelLevel)
NameError: name 'Car' is not defined
回溯(最近一次呼叫最后一次):
文件“C:\Users\John\Desktop\prog4.py”,第5行,在
等级车:
文件“C:\Users\John\Desktop\prog4.py”,第47行,车内
main()
文件“C:\Users\John\Desktop\prog4.py”,第33行,在main中
加仑汽油=汽车(燃油水平)
NameError:未定义名称“Car”

我仍然收到一个NameError,指出Car(类)未定义。我做错了什么?

您忘记了
main
中的
fueleficiency
参数:

def main():
    print("Fuel Estimator")

    fuelEfficiency = float(input('MPG: '))
    fuelLevel = float(input('Fuel: '))
    miles = float(input('Distance: '))
    # gallonsRemaining = Car(fuelLevel) <- one argument is missing in __init__
    gallonsRemaining = Car(fuelEfficiency, fuelLevel)

    while True:
        x = input("Would you like to enter another (y/n): ")

        if x == "y":
            main()
            continue
        elif x == "n":
            break
        else:
            print("Would you like to enter another (y/n): ")
def main():
打印(“燃油估计器”)
燃油效率=浮动(输入('MPG:'))
燃油液位=浮动(输入('Fuel:'))
英里=浮动(输入('距离:'))

#gallonsRemaining=Car(fuelLevel)请修复缩进。这是python 3还是python 2?此外,缩进也是错误的。所有方法都应该从类def缩进。您还可以扔掉fuelevel参数。这是Python3。显示完整的回溯——复制并粘贴到您的question@ettanany我认为edit在解决一些问题的同时,也引入了缩进问题
def main()
如果_uname\u uu…
通常不在类中。无法帮助您,因为添加缺少的参数后,您的代码在我的计算机上运行时不会出现任何错误。