【问题标题】:unbound method must be called with instance as first argument (got nothing instead)必须以实例作为第一个参数调用未绑定的方法(而不是什么都没有)
【发布时间】:2013-10-18 05:48:55
【问题描述】:

我试图从一个继承中移动所有类。 我写了这个小脚本:

class c1:
    def move():
        x+=1
        y+=1
class c2(c1):
    y=1
    x=2
c=c2
c.move()
print(str(c.x)+" , "+str(c.y))

当我运行它时,我得到:

Traceback (most recent call last):   File "/home/tor/Workspace/try.py", line 9, in <module>
     c.move() TypeError: unbound method move() must be called with c2 instance as first argument (got nothing instead) [Finished in 0.1s
with exit code 1]

我做错了什么?

【问题讨论】:

  • 你没有实例化任何类。
  • 你的意思是c = c2()c.move()吗?
  • 你需要先了解Classes:docs.python.org/2/tutorial/classes.html
  • 上面的教程适合那些已经熟悉类(可能是另一种语言)并想看看它们在python中是如何工作的,从一开始就学习类并不是很好。对于大多数初学者来说,课程的整个概念令人困惑,因此即使付出了努力,也可能会离开。

标签: python class inheritance


【解决方案1】:
  1. 你没有实例化任何东西

  2. 所有方法都必须至少采用一个参数,传统上称为self

  3. 您需要self 才能访问对象字段。您的代码现在修改了该范围内不存在的局部变量。

【讨论】:

    猜你喜欢
    • 2017-12-23
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2014-09-10
    相关资源
    最近更新 更多