Reputation: 67
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
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
Reputation: 2596
There are two ways.
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]
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