Python 属性错误:';1类';对象没有属性';追加';
一个关于课程的蹩脚问题:Python 属性错误:';1类';对象没有属性';追加';,python,python-3.x,Python,Python 3.x,一个关于课程的蹩脚问题: 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) 我得到:AttributeError:'class1'对象没有属性'append' 我做错了什么?您不能只将列表分配给self;
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)
我得到:AttributeError:'class1'对象没有属性'append'
我做错了什么?您不能只将列表分配给
self
;您所做的只是将本地名称重新绑定到列表对象
您必须对列表
类型进行子类化:
class class1(list):
def insert1(self, x):
self.append(x)
或将新列表对象指定给self
上的属性:
class class1:
def __init__(self):
self._lst = []
def insert1(self, x):
self._lst.append(x)