Gilgamesch Gilgamesch - 1 year ago 165
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
def stats(self):
print 'Leben: '
print self.leben
print 'Geschwindigkeit: '
print self.speed
print 'Schaden: '
print self.SD

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

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

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 Source


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

this line:


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 = 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 ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download