I am trying to create a simple class that inputs a list then appends to the list with a function called "add" which is also defined in the same class.
I keep getting this error: 'list' object has no attribute 'a'
class try1:
def __init__(self, a=[]):
self.a = a
print(a)
return
def add(self, b=None):
self.a.append(b)
print(a)
return
if __name__ == "__main__":
c=try1(['a', 'b', 'c'])
d = ['d', 'e', 'f']
try1.add(d)
I think there's an indentation problem here. Please post your code with python tags so that we can see the indentation. See the BBCode link in my signature for instructions.
That said, using an empty list as a default parameter is a bad idea. You should use None, and if the parameter is None, replace it with an empty list. Also, I would not give b a default value. The method doesn't make sense without a parameter, so let it cause an error if one isn't given. I also think it may be masking the problem you are having.
Thanks for the reply!
I've updated the code per your recommendations :)
class try1:
def __init__(self, a=None):
self.a = a
print(a)
return
def add(self, b):
self.a.extend(b)
print(a)
return
if __name__ == "__main__":
c=try1(['a', 'b', 'c'])
d = ['d', 'e', 'f']
try1.add(d)
Your last line should be
c.add(d)
. You want to call it from the instance, so the instance parameter (self) is automatically filled. Also note that the print in the add method should be
print(self.a)
, since a is an attribute of the instance. Finally, what I was talking about with the a parameter to __init__ was more like this:
def __init__(self, a = None):
if a is None:
a = []
self.a = a
print(a)
Inside the class, you keep printing 'a' but this is the passed argument which is always the same since you don't alter it. Do you mean to print self.a?