使用类中的列表的属性错误 - python

-2 python constructor class python-2.7

我收到了属性错误.无法理解为什么.请帮忙.

class List:
    def _init_(self):
        self.A=[]
    def Input(self):
        self.A.append("Sam")
        a=input("Enter no.")
        self.A.append(a)
        print "No. added successfully"
    def Output(self):
        print "The list is:"
        for i in range(len(self.A)):
            print self.A[i]

b=List()
b.Input()
b.Output()
Run Code Online (Sandbox Code Playgroud)

Mik*_*ler 5

更改:

def _init_(self):
Run Code Online (Sandbox Code Playgroud)

成:

def __init__(self):
Run Code Online (Sandbox Code Playgroud)

2个开头和结尾的下划线是很重要的.

如果Python找不到__init__方法,则从中获取一个方法,object当然不会添加属性A.说到objectPython 2,你应该总是继承形式object:

class List(object):
Run Code Online (Sandbox Code Playgroud)

获得新式课程.

或者只是切换到Python 3.