0
How to access a variable in one python function in another function (python)
import requests class location: def __init__(self,city): self.city=city def ct(self): global req_read req=requests.get(self.city) req_read=req.text return req_read def ct_2(self): global req_read return req_read a=location("https://www.metaweather.com/api/location/search/?query=paris") print(a.ct_2())
3 Respuestas
+ 1
I believe you can do:
def __init__(self, city):
self.city = city
self.req_read = ''
...and refer to your req_read variable using self.req_read everywhere else in your class. This means you don't need your global req_read statements.
Hope this is what you wanted.
+ 3
Pass it as an argument to the function.
For a free (not in a class) function for example:
def f(x, y):
# Do stuff with x and y
call it like this:
f(value1, value2)
# value1 and value2 being
# the values you want to use
For class methods:
class C:
def f(self, x, y):
# Do stuff with x and y
Make an instance, then call the method like this:
c = C()
c.f(value1, value2)
0
thank you