所以我有一个带函数的类。我想在另一个函数中使用一个函数来计算燃油消耗量。你知道吗
我有这个属性自我消费,在函数Calculate_consumption
中计算。你知道吗
现在我想写一个新的函数,它更新公里数计数器,并计算你的驾驶效率。你知道吗
所以,我想用函数Claculate_consumption
来计算消耗量,然后看看它是否大于8。你知道吗
我试着编写这个函数,就像我在Stackoverflow上发现的那样:How do you call a function in a function?
但这个解决方案不知何故不起作用。也许有人能指出我的错误。你知道吗
class Car:
def __init__(self, kmDigit):
self.kmDigit = int(kmDigit)
self.Max = 8
self.consumption = 0
def Claculate_consumption(self, Liter, km):
self.consumption += (Liter/km)*100
return round(self.consumption, 2)
def Refuel(self,Liter, km):
self.kmDigit += km
print self.kmDigit
a = Claculate_consumption(Liter, km)
if a > self.Max:
b = self.consumption - self.Max
print 'Your fuel consumption is too high!'
else:
print 'Nice!'
我在第14行得到一个**NameError**
,因为Calculate_consumption
在某种程度上是一个global name
。你知道吗
你必须写:
a = self.Claculate_consumption(Liter, km)
因为您的程序不知道在何处查找此方法。Self表示此方法与调用该方法的类在同一个类中相关问题 更多 >
编程相关推荐