【问题标题】:What is the meaning of error "... object has no attribute ..."?错误“...对象没有属性...”是什么意思?
【发布时间】:2016-02-02 09:40:53
【问题描述】:

考虑:

代码

class sand:
    def __init__(self):
        print("I am a pickle")
        def next(self):
            print("I am a tuner")

测试和输出

>>> x = sand()
I am a pickle
>>> x.next()
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    x.next()
AttributeError: 'sand' object has no attribute 'next'

【问题讨论】:

    标签: python class object methods


    【解决方案1】:

    没有属性next 因为你的缩进不正确。使用:

    class sand:
        def __init__(self):
            print("I am a pickle")
    
        def next(self):
            print("I am a tuner")
    
    x = sand()
    x.next()
    

    输出

    I am a pickle
    I am a tuner
    

    【讨论】:

    • 谢谢,但它可以告诉我吗?
    • 公平地说,它已经尽力了。原始代码是完美有效的 Python,您只是没有访问本地定义的方法,而您认为是。当您所说的内容有所不同时,口译员无法理解您的意思。
    【解决方案2】:

    请检查缩进。

    >>> class sand:
    ...   def __init__(self):
    ...      print("i am a pickle")
    ...   def next(self):
    ...      print("I am a tuner")
    ...
    >>> x = sand()
    i am a pickle
    >>> x.next()
    I am a tuner
    

    【讨论】:

      【解决方案3】:

      您将next 定义为__init__ 中的内部函数,这就是为什么它不是sand 的类属性,因此您会得到AttributeError

      next 移出__init__ 即可:

      class sand:
          def __init__(self):
              print("i am a pickle")
          def next(self):
              print("I am a tuner")
      

      【讨论】:

        猜你喜欢
        • 2018-02-18
        • 2019-10-31
        • 1970-01-01
        • 2020-11-24
        • 2019-12-23
        • 1970-01-01
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多