在函数中使用函数

2024-05-16 04:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个带函数的类。我想在另一个函数中使用一个函数来计算燃油消耗量。你知道吗

我有这个属性自我消费,在函数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。你知道吗


Tags: 函数self属性deffunctionmaxprintcalculate
1条回答
网友
1楼 · 发布于 2024-05-16 04:38:26

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

self : self represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the class in python. https://micropyramid.com/blog/understand-self-and-init-method-in-python-class/

相关问题 更多 >