必须以实例作为第一个参数调用未绑定方法(代之以无用)


问题内容

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

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]

我做错了什么?


问题答案:
  1. 您不实例化任何东西

  2. 所有方法都必须至少采用一个通常称为的参数self

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