igorkf
igorkf

Reputation: 3565

Access a list that is inside a function that is inside a class

Suppose that I have a class like this one in a.py file:

class MyClass():
    def get(self, request, format='json'):
        pipeline = ['something_here']

How can I access the list pipeline from another file like b.py?
a.py and b.py are in the same directory.

I'm trying something like this:

from a import MyClass

my_list = MyClass.pipeline

OBS.: I can't change the a.py file because other people are using it.

Upvotes: 1

Views: 555

Answers (3)

A. Abramov
A. Abramov

Reputation: 1865

You can't access it directly. What you could do is either return it, receive it as an attribute of the instance, or make it a global class variable.

Upvotes: 3

Hampus Larsson
Hampus Larsson

Reputation: 3100

One solution for this problem, is to use inheritance, and just change the logic for MyClass inside of a new class.

Given the following contents of a.py:

class MyClass:
    def __init__(self, x,y,z):
        self.x = x
        self.y = y
        self.z = z

    def get(self, somestring):
        pipeline = [somestring]
        return pipeline

Creating a new object of MyClass and calling get("somestring"), will return a list containing just that string. However, we do not set the property inside of the class, so it's only available inside of the method itself.

Creating a new file, in this case b.py, we can create a new class, inheriting from the first class, and just modify the get method to have the logic we want.

from a import MyClass

class MyNewClass(MyClass):
    def get(self, somestring):
        self.pipeline = [somestring]

Inside of b.py we can then do the following test:

old = MyClass(1,2,3)
print(old.x, old.y, old.z)
print(old.get("this is the input-string"))

new = MyNewClass(4,5,6)
print(new.x, new.y, new.z)
new.get("This is the second input-string")
print(new.pipeline)

Output:

1 2 3
['this is the input-string']
4 5 6
['This is the second input-string']

Upvotes: 1

Moosa Saadat
Moosa Saadat

Reputation: 1167

As you can't change a.py, it is not possible to access this list. This list needs to be declared as a data member of MyClass or it needs to be returned from MyClass.get(). Otherwise, it is not possible

Upvotes: 2

Related Questions