【发布时间】:2019-01-13 15:41:46
【问题描述】:
所以我有一个具有一些功能的类。我想在另一个函数中使用一个函数来计算油耗。
我有 self.consumption 属性,它是在函数 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) -
你拼错了计算。虽然看起来你一直这样做,所以不会导致错误。
标签: python python-2.7 function class