【问题标题】:Python: variable scope and "instance has no attribute"Python:变量范围和“实例没有属性”
【发布时间】: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

Python - Access class variable from instance

Python Variable Scope and Classes instance has no attribute

【问题讨论】:

  • _init__ 开头只有一个下划线。它需要两个。

标签: python scope


【解决方案1】:

您定义了一个名为 _init__ 的方法,而不是 __init__。下划线的数量很重要。如果没有 exact 正确的名称,它只是一个奇怪的命名方法,根本不是实例初始化程序。您最终使用默认初始化程序(不设置任何属性)。您的_init__ 也有错误(您指的是l 不合格)。修复这两个,您的初始化程序将是:

def __init__(self):    # <-- Fix name
    print "initializer called"
    #l is an instance variable
    self.l = []
    print len(self.l)  # <-- Use self.l; no local attribute named l

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2015-03-22
    • 2017-12-08
    相关资源
    最近更新 更多