繁体   English   中英

Python TypeError:必须以实例作为第一个参数调用未绑定方法

[英]Python TypeError: unbound method must be called with instance as first argument

因此,我尝试编写基于终端的RPG以便学习OOP,因此我编写了以下代码:

class car(object):  #car is the short form of Character
  def __init__(self):
    self.leben = 100
    self.speed = 10
    self.SD = 20
  def attack(self, life):
    #life-= self.SD
    #return life
    pass
  def stats(self):
    print 'Leben: '
    print self.leben
    print 'Geschwindigkeit: ' 
    print self.speed
    print 'Schaden: '
    print self.SD

class wojok(car): 
  def __init__(self):
    super(car.__init__(self)).__init__()
    self.SD = 50


C = wojok()
while True:
  e = raw_input('Befehl: ')
  if e == 'info':
    C.stats()
  elif e == 'stop':
    break

现在我得到了错误:

TypeError: unbound method __init__() must be called with car instance as first argument(got nothing instead)

但是,当我尝试将car的实例作为第一个参数传递给init时,出现错误:

TypeError: unbound method __init__() must be called with car instance as first argument(got instance instead)

我首先要使用什么?

class wojok(car): 
  def __init__(self):

这行:

    super(car.__init__(self)).__init__()

应该

    super(wojok, self).__init__() 

但是,如果您只想拥有具有不同属性值的不同car实例,只需将它们传递给初始化程序(可能具有默认值)即可:

class Character(object):
    def __init__(self, leben=100, speed=10, sd=20):
        self.leben = leben
        self.speed = speed
        self.sd = sd

然后,您可以实例化不带任何参数的Character以获得默认值或指定所需的值,即:

default_char = Character()
special_char = Character(sd=100)

注:蟒蛇命名约定:使用CapCase上课, all_lower变量和函数,以及ALL_UPPER伪常数,并且更喜欢描述性名称的缩写(除非缩写是真的本身就是一个“描述性的名字)。

当然,如果wojok实例的行为应与“标准” Character (并且您将其省略,因为它与此处无关),则子类化是一个合适的解决方案;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM