Gilgamesch Gilgamesch - 7 months ago 31
Python Question

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

So I tried to write an terminal based RPG in order to learn OOP, so I wrote this code:

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


Now I get the error:

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


But when I try to pass an instance of car as the first argument into init I get the error:

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


What do I have to use as first argument?

Answer

in

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

this line:

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

should be

    super(wojok, self).__init__() 

But if all you want is to have different car instances with different attributes values, just pass them to the initializer (possibly with default values) :

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

Then you either instantiate Character with no arguments to get the default values or specify what you want, i.e.:

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

NB : python naming conventions: use CapCase for classes, all_lower for variables and functions, and ALL_UPPER for pseudo-constants, and prefer descriptive names to abbreviations (unless the abbreviation is really a 'descriptive' name by itself).

Of course if a wojok instance is supposed to have a different behaviour from a "standard" Character (and you omitted it because it's not relevant here) subclassing is an appropriate solution ;)