属性未定义错误,即使它是在全局范围上定义的

2024-10-16 17:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,所以请容忍我。我正在制作一个包含汽车的品牌、型号和燃料的类,并在试验set和get方法来尝试和学习它们的用法。我遇到的问题是,当我试图通过运行我的setFuel方法来更新我的tank属性并打印出更新后的fuel整数时,我得到了错误tank is not defined,尽管我已经在上面定义了它。为什么会发生这种情况?我如何修复它

我在我的代码中添加了注释,以解释我试图做什么来帮助您理解我的代码。任何帮助都将受到感谢

class Car:
    tank = 0 #to keep track of fuel
    make = ""
    model = "" #to keep track of model
    
    def __init__(self, make, model, fuel):
        self.make = make
        self.model = model
        self.fuel = fuel
        

    #returns the amout of fuel currently in the tank(as an integer)   
    def getFuel(self):
        return int(self.fuel)

    #sets the amounts of fuel currently in the tank(as an integer)
    def setFuel(self, tank):
        self.tank = int(tank)

    #returns the make and model of the car as a string
    def getType(self):
        return str(self.make),(self.model)

    def printFuel(self):
        print(self.fuel)

#Instantiate a new Car in a variable
myCar = Car("Ford", "Escort", 10)
yourCar = Car("Ford", "Escape", 14)

#print statement that prints the result of the "getFuel"
#method of the "myCar" object
myCar.printFuel()
yourCar.printFuel()

#Change the "tank" attribute to modify the fuel in the tank using
#setFuel method of the "myCar" and "yourCar" object
#subtract 7 from from the tank
myCar.setFuel(tank-7)
#subtract 5 from the tank 
yourCar.setFuel(tank-5)

#print statement that prints the result of the "getFuel"
#method of the "myCar" and "yourCar" object
print(myCar.getFuel())
print(yourCar.getFuel())
print(myCar.getType())
print(yourCar.getType())

Tags: oftheinselfmakemodeldefcar
2条回答

这样做:

class Car:
    tank = 0 
    make = ""
    model = "" 

tankmakemodel是所有实例共享的类变量,因此myCaryourCar将共享相同的tank。有关Class and Instance Variables的更多详细信息,请阅读Python文档

因为汽车的油箱是每辆汽车(每个实例)的一部分,所以最好使用实例变量。因此最好将这些变量写入__init__

class Car:
    def __init__(self, make, model, fuel):
        self.tank = 0 
        self.make = make
        self.model = model
        self.fuel = fuel

现在,tank是一个实例变量。要访问它,请使用myCar.tank(此处myCar是对象Car的实例)。因此,要从油箱中减去燃油,请执行以下操作:

myCar.setFuel(myCar.tank - 7)

编辑:您的代码在打印时没有减少燃油,因为您的代码存在另一个问题。看看你的setFuel函数,它设置的是tank,而不是fuel。改为:

def setFuel(self, fuel):
    self.fuel = int(fuel)

另外,在myCar中设置燃油时,使用的是myCar.tank - 7,其中tank等于0。因此,您需要做的是:

myCar.setFuel(myCar.fuel - 7)

我认为更好的办法是在Car对象中创建一个函数来减少燃油,并在这个函数中检查汽车是否有足够的燃油(因为你不能有-x燃油,对吗?),如下所示:

def reduceFuel(self, fuel_used):
    if self.fuel - fuel_used < 0:
        raise ValueError("Not enough fuel")
    else:
        self.fuel -= fuel_used

以及使用:

myCar.reduceFuel(7)

您需要myCar.setFuel(myCar.tank-7)yourCar.setFuel(yourCar.tank-5)。您可以考虑添加^ {< CD3> }方法,使之更容易。

相关问题 更多 >