【发布时间】:2018-02-06 04:13:08
【问题描述】:
我对 python 中的实例和类变量感到困惑。我对这段代码的方式感到困惑:
class A:
def _init__(self):
print "initializer called"
#l is an instance variable
self.l = []
print len(l)
def printList(self):
print len(self.l)
a = A()
print "here"
a.printList()
产生以下输出:
here
Traceback (most recent call last):
File "C:\Python27\a.py", line 16, in <module>
a.printList()
File "C:\Python27\a.py", line 10, in printList
print len(self.l)
AttributeError: A instance has no attribute 'l'
没有调用初始化程序吗?为什么“这里”打印,但初始化程序中的打印语句没有? 'l' 应该是一个类变量吗?我认为使用'self'将其作为实例变量就足够了,这不正确吗?我对这些变量的范围不正确吗?
我查看了这些来源,但它们没有帮助:
Python: instance has no attribute
Python: Difference between class and instance attributes
【问题讨论】:
-
_init__开头只有一个下划线。它需要两个。