-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)
更改:
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.
| 归档时间: |
|
| 查看次数: |
34 次 |
| 最近记录: |