[英]Attribute not defined error, even though it is defined on a global scope
我是 python 的新手,所以請多多包涵。 我正在制作一個 class,其中包含汽車的品牌、model 和燃料,並且正在嘗試使用 set 和 get 方法來嘗試和學習它們的使用。 我遇到的問題是當我嘗試通過運行我的setFuel
方法來更新我的tank
屬性並打印出更新的燃料 integer 我得到錯誤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())
這樣做:
class Car:
tank = 0
make = ""
model = ""
tank
、 make
和model
是所有實例共享的 class 變量,因此myCar
和yourCar
將共享同一個tank
。 閱讀 Python 文檔,了解有關Class 和實例變量的更多詳細信息。
因為汽車的油箱是每輛車(每個實例)的一部分,所以最好使用實例變量。 所以最好在__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
是 object Car
的一個實例)。 因此,要從油箱中減去燃料,請執行以下操作:
myCar.setFuel(myCar.tank - 7)
編輯:您的代碼在打印時並沒有減少燃料,因為您的代碼還有另一個問題。 看看你的setFuel
function,它是在設置tank
而不是fuel
。 改成:
def setFuel(self, fuel):
self.fuel = int(fuel)
此外,當您在myCar
中設置燃料時,您正在使用myCar.tank - 7
,其中tank
等於0
。 所以你需要做的是:
myCar.setFuel(myCar.fuel - 7)
我認為一個更好的主意是在Car
object 內制造一個 function 以減少燃料,在這個-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)
。 您可能會考慮添加一個useFuel
方法以使其更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.