错误“...对象没有属性......”是什么意思?

时间:2016-02-02 09:40:53

标签: python class object methods

考虑:

代码

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'

3 个答案:

答案 0 :(得分:2)

没有属性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

答案 1 :(得分:0)

请检查缩进。

>>> 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

答案 2 :(得分:0)

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

next移出__init__,它会起作用:

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