Passing Variables Between Methods In 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
Solution 1:
These need to be instance variables:
classsimpleclass(object):
def__init__(self):
self.x = None
self.y = Nonedefgetinput (self):
self.x = input("input value for x: ")
self.y = input("input value for y: ")
defcalculate (self, z):
print self.x+self.y+z
Solution 2:
You want to use self.x
and self.y
. Like so:
classsimpleclass (object):
defgetinput (self):
self.x = input("input value for x: ")
self.y = input("input value for y: ")
defcalculate (self, z):
print self.x+self.y+z
Solution 3:
x
and y
are local variables. they get destroyed when you move out from the scope of that function.
classsimpleclass (object):
defgetinput (self):
self.x = raw_input("input value for x: ")
self.y = raw_input("input value for y: ")
defcalculate (self, z):
printint(self.x)+int(self.y)+z
Solution 4:
Inside classes, there's a variable called self
you can use:
classExample(object):
defgetinput(self):
self.x = input("input value for x: ")
defcalculate(self, z):
print self.x + z
Solution 5:
classmyClass(object):
def__init__(self):
defhelper(self, jsonInputFile):
values = jsonInputFile['values']
ip = values['ip']
username = values['user']
password = values['password']
return values, ip, username, password
defcheckHostname(self, jsonInputFile):
values, ip, username, password = self.helper
print values
print'---------'print ip
print username
print password
the init method initializes the class. the helper function just holds some variables/data/attributes and releases them to other methods when you call it. Here jsonInputFile is some json. the checkHostname is a method written to log into some device/server and check the hostname but it needs ip, username and password for that and that is provided by calling the helper method.
Post a Comment for "Passing Variables Between Methods In Python?"