learningpal learningpal - 16 days ago 5
Python Question

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

I am new to python and trying to figure out the issues in my first python code. I am taking an input

temp
from user in method
parameter
and i want to compare this
temp
with another variable
oven_temp
in
make_item
method. But I get a
NameError
that name
temp
is not defined. I read some posts here and it was mentioned that I had to return value from a method. I returned it but not getting exactly how to proceed.

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()

Answer

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()
Comments