我是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())
这样做:
tank
、make
和model
是所有实例共享的类变量,因此myCar
和yourCar
将共享相同的tank
。有关Class and Instance Variables的更多详细信息,请阅读Python文档因为汽车的油箱是每辆汽车(每个实例)的一部分,所以最好使用实例变量。因此最好将这些变量写入
__init__
:现在,
tank
是一个实例变量。要访问它,请使用myCar.tank
(此处myCar
是对象Car
的实例)。因此,要从油箱中减去燃油,请执行以下操作:编辑:您的代码在打印时没有减少燃油,因为您的代码存在另一个问题。看看你的
setFuel
函数,它设置的是tank
,而不是fuel
。改为:另外,在
myCar
中设置燃油时,使用的是myCar.tank - 7
,其中tank
等于0
。因此,您需要做的是:我认为更好的办法是在
Car
对象中创建一个函数来减少燃油,并在这个函数中检查汽车是否有足够的燃油(因为你不能有-x
燃油,对吗?),如下所示:以及使用:
您需要
myCar.setFuel(myCar.tank-7)
和yourCar.setFuel(yourCar.tank-5)
。您可以考虑添加^ {< CD3> }方法,使之更容易。相关问题 更多 >
编程相关推荐