Reputation: 906
How do I access a list from a class constructor in python, to use in another class method? For example:
Class Data():
def __init__(self):
list1 = ["a", "e", "i", "o", "u"]
def __length__():
length = len(list1)
print(length)
To print the length of the current list.
Upvotes: 0
Views: 209
Reputation: 6551
To solve your problem, you should use instance attributes:
class Data():
def __init__(self):
self.list1 = ["a", "e", "i", "o", "u"]
def __length__(self):
length = len(self.list1)
print length
The idea here is not that you're "accessing the constructor", but you are accessing an attribute of an instance of this class. The class Data
might have attributes: list1
, 'list2,
vowels,
consonants`, you name it. You will want to set these in the constructor, and then you can change or access them in class methods.
But perhaps you could do even better. Consider these two thoughts:
__length__
? Perhaps something more descriptive (and less abusive of those underscores) would help e.g. def print_number_of_vowels(self)
.Data
is a pretty vague, considering making it more specific e.g. AlphabetData
.Perhaps something more like:
class AlphabetData():
def __init__(self):
self.vowels = ["a", "e", "i", "o", "u"]
def print_number_of_vowels(self):
print len(self.vowels)
Upvotes: 1
Reputation: 578
You need use self attribue, according python code style "Always use self for the first argument to instance methods.", Try this :
class Data():
def __init__(self):
self.list1 = ["a", "e", "i", "o", "u"]
def __length__(self):
length = len(self.list1)
print(length)
Upvotes: 2
Reputation: 40894
Pay attention to the self
parameter passed to every instance method. It's the instance itself. It's like this
in C++ or Java, just passed explicitly. And you should use it explicitly (type import this
if in doubt).
So, as other posters mentioned, you need something like this:
class Data():
def __init__(self):
self.vowels = ['a', 'e', 'u', 'i', 'o']
def __len__(self): # if you want to use len() on your object
return len(self.vowels) # refer to the list defined in constructor
Upvotes: 3