How to pass variable of one method in other method within the same class in Python

Question:

I am taking an input temp from user in method parameter and I want to compare this temp with another variable oven_temp in the make_item method. But I get a NameError, saying that name temp is not defined.

I read some posts here and I understood that I need to return the value from the method – so I did that; but now what? Specifically, I tried:

class maker:
    def parameter(self):
        temp = int(input('At what temperature do you want to make n'))
        return temp

    def make_item(self):
        def oven (self):
            oven_temp = 0
            while (oven_temp is not temp):
                oven_temp += 1
                print ("waiting for right oven temp")
        oven(self)

person = maker()
person.parameter()
person.make_item()

but I still get the NameError. How do I fix it?

Asked By: learningpal

||

Answers:

Keep it in yourself!

class MyMaker:
    def ask_temperature(self):
        self.temp = int(input('Temperature? n'))

    def print_temperature(self):
       print("temp", self.temp)

Try it:

> maker = MyMaker()
> maker.ask_temperature()
Temperature?
4
> maker.print_temperature()
temp 4
Answered By: slezica

The following should work to solve your problem. Basically, you want to store the variables you want to pass between methods as members of the class. You do this by assigning an attribute of the self parameter to the functions.

 class maker:
    def parameter(self):
        self.temp = int (input ('At what temperature do you want to make n'))


    def make_item (self):
        def oven ():
            oven_temp = 0
            while (oven_temp is not self.temp):
                oven_temp += 1
                print ("waiting for right oven temp")

        oven()


person = maker ()
person.parameter()
person.make_item()
Answered By: Anthony Oteri

This is another way as to how you can return value from one method and pass the same to another method and finally print the result.

class Maker():

    def parameter(self):
        temp = int(input('At what temperature do you want to make n'))
        return temp

    def make_item(self,temp):
        def oven():
            oven_temp = 0
            while (oven_temp is not temp):
                oven_temp += 1
                print ("waiting for right oven temp")
            return oven_temp

        return oven()


person = Maker()
val = person.parameter()
print(person.make_item(val))

Output:

waiting for right oven temp
waiting for right oven temp
waiting for right oven temp
waiting for right oven temp
4
Answered By: robots.txt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.