Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables between methods in Python?

Tags:

python

I have a class and two methods. One method gets input from the user and stores it in two variables, x and y. I want another method that accepts an input so adds that input to x and y. Like so:

class simpleclass(object):
    def getinput(self):
        x = input("input value for x: ")
        y = input("input value for y: ")
    def calculate(self, z):
        print(x + y + z)

When I run calculate(z) for some number z, it gives me errors saying the global variables x and y aren't defined.

How can calculate get access to the x and y values that were assigned in getinput?

like image 909
monolith Avatar asked Nov 27 '22 22:11

monolith


1 Answers

These need to be instance variables:

class simpleclass(object):
    def __init__(self):
        self.x = None
        self.y = None

    def getinput(self):
        self.x = input("input value for x: ")
        self.y = input("input value for y: ")
   
    def calculate(self, z):
        print(self.x + self.y + z)
like image 88
turtlebender Avatar answered Dec 06 '22 16:12

turtlebender