在函数中使用函数

时间:2019-01-13 15:41:47

标签: python python-2.7 function class

所以我有一个带有某些功能的类。我想在另一个函数中使用一个函数来计算燃油消耗。

我具有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

1 个答案:

答案 0 :(得分:3)

您必须写:a = self.Claculate_consumption(Liter, km) 因为您的程序不知道在哪里寻找该方法。 自我说,该方法与您调用该方法的类别相同

  

self:self表示类的实例。通过使用“ self”关键字,我们可以在python中访问该类的属性和方法。   https://micropyramid.com/blog/understand-self-and-init-method-in-python-class/

相关问题