1

A lame question regarding Classes:

class class1:

  def __init__(self):
    self = []

  def insert1(self,x):
    self.append(x) /// the object is a list in which x to be appended

a = class1()
a.insert1(5)

And I get: AttributeError: 'class1' object has no attribute 'append'

What am I doing wrong?

1 Answer 1

2

You cannot just assign a list to self; all you did was rebind the local name to a list object.

You'll either have to subclass the list type:

class class1(list):
    def insert1(self, x):
        self.append(x)

or assign a new list object to an attribute on self:

class class1:
    def __init__(self):
        self._lst = []

    def insert1(self, x):
        self._lst.append(x)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.