Vaibhav Saxena
Vaibhav Saxena

Reputation: 67

How to access a list in a function in a class?

I have a list to which I am appending values. It's in a function which is in a class. How do I access it?

class A:
   def __init__(self):
        #my variables

   def myfunction(self):
       myList = []
       for i in range(5):
          myList.append(i)


myobj = A()
myobj.myfunction()

I want to get the list myList.

Upvotes: 0

Views: 77

Answers (2)

Chayan Bansal
Chayan Bansal

Reputation: 2085

Better implementation would have been:

class A:
    def __init__(self):
        self.__myList =[]

    def myfunction(self):
        for i in range(5):
            self.__myList.append(i)
    @property
    def myList(self):
        return self.__myList.copy()

And then using it as:

myobj = A()
myobj.myfunction()
print(myobj.myList)

Upvotes: 4

Boseong Choi
Boseong Choi

Reputation: 2596

There are two ways.


1. Make it attribute

class A:
    def __init__(self):
        self.my_list = []

    def my_function(self):
        self.my_list = []
        for i in range(5):
            self.my_list.append(i)


a = A()
a.my_function()
print(a.my_list)

output:

[0, 1, 2, 3, 4]

2. Return the list

class A:
    def my_function(self):
        my_list = []
        for i in range(5):
            my_list.append(i)
        return my_list


a = A()
result = a.my_function()
print(result)

output:

[0, 1, 2, 3, 4]

Upvotes: 5

Related Questions