0

So I have a class with some functions. I want to use a function in another function to calculate the fuelconsumption.

I have the attribute self.consumption, which is calculated within the function Calculate_consumption.

Now I want to write a new function, which is updating the kilometer counter and also calculating if you are driving efficient.

So, I want to calculate the consumption by using the function Claculate_consumption and then see if it is bigger then 8 or not.

Well I tried to just write the function as I have found it here on Stackoverflow: How do you call a function in a function?

But this solution somehow does not work. Maybe somebody can point out my mistake.

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!'

I am getting a **NameError** in line 14, because Calculate_consumption is somehow a global name.

2
  • 6
    use a = self.Claculate_consumption(Liter, km) Commented Jan 13, 2019 at 15:43
  • 1
    You're misspelling Calculate. Although looks like you have done so consistently so doesn't contribute to an error. Commented Jan 13, 2019 at 15:49

1 Answer 1

3

You have to write: a = self.Claculate_consumption(Liter, km) because your program does not know where to look for this method. Self says that this method is in the same class in which you call the method

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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.