1

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)
wwii
  • 23,232
  • 7
  • 37
  • 77

2 Answers2

4

You've got a couple different things going on here which cause this weird-looking error.

The core problem is that you're trying to call add on the class try1, not the instance you just created, in the variable c. Changing try1.add(d) to c.add(d) produces the expected result (if you also remove the print(a) or change it to print(self.a), since a doesn't exist in that scope).

The unrelated-looking error is because you made b a keyword argument. When you try to call try1.add, the first argument becomes self inside the method. Then you get an AttributeError because self is a list, which obviously doesn't have an attribute named a.

Also, you shouldn't use a mutable as a default argument. Additionally, you don't need empty return statements: any function without a return statement implicitly returns None.

Josh Karpel
  • 2,110
  • 2
  • 10
  • 21
  • Thank you!! I appreciate the added clarifying info as well! I'm a very green coder so everything is a bit overwhelming rn. – Ilya Josefson Oct 14 '17 at 23:16
0

A few things here. First of all, fix that indentation. Python is really specific about whitespace. Assuming you fix the indentation, you'll come into a couple of other issues. In your main method, you want to be calling c.add(d) (I think).

You're probably running into an error on line 9, which is the error I think you're talking about. In the scope of your method, the variable a doesn't exist yet. self.a does, though. You probably mean to print self.a.

As a side note, class names in Python should start with an uppercase letter. Numbers are allowed, but I'd really try and avoid them.

mrantry
  • 13
  • 5