Access variable from one function to another

Question:

I have a following code snippet in python.

class Test():
    def a(self,dct,res_dct,lst):
        url_ls = []
        ....
        return url_ls
   
    def b(self):
        ....

I want to access the url_ls from a() to b(). How is it possible?

Asked By: Joz

||

Answers:

Why not making url_ls a class attribute? then you can acess it from every method. self.url_ls

class Test():
    def __init__(self):
        self.urls_ls = []

    def a(self,dct,res_dct,lst):
        url_ls = []
        ....
        self.urls_ls = url_ls
   
    def b(self):
        ....
Answered By: Nikolay Zakirov

You need to initialize a instance attribut ”’self.urls”’.
After that, you can use it in both function (see doc POO)

class Test():
def __init__(self):
    self.url_ls = []

def a(self,dct,res_dct,lst):
    self.url_ls = []

def b(self):
    print(self.url_ls)
Answered By: Adrien Derouene
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.