Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 属性错误:';1类';对象没有属性';追加';_Python_Python 3.x - Fatal编程技术网

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)