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
?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With