【问题标题】:Using a function within a function在函数中使用函数
【发布时间】: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


【解决方案1】:

你必须写:a = self.Claculate_consumption(Liter, km) 因为你的程序不知道去哪里找这个方法。 Self 表示此方法在您调用该方法的同一类中

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

【讨论】:

    猜你喜欢
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2019-05-03
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多