Friday 15 January 2010

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



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

so tried write terminal based rpg in order larn oop, wrote code:

class car(object): #car 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 error:

typeerror: unbound method __init__() must called auto instance first argument(got nil instead)

but when seek pass instance of auto first argument init error:

typeerror: unbound method __init__() must called auto instance first argument(got instance instead)

what have utilize first argument?

in

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

this line:

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

should be

super(wojok, self).__init__()

but if want have different car instances different attributes values, pass them initializer (possibily default values) :

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

then either instanciate character no arguments default values or specify want, ie:

default_char = character() special_char = character(sd=100)

nb : python naming conventions: utilize capcase classes, all_lower variables , functions, , all_upper pseudo-constants, , prefer descriptive names abbreviations (unless abbreviation 'descriptive' name itself).

of course of study if wojok instance supposed have different behaviour "standard" character (and omitted because it's not relevant here) subclassing appropriate solution ;)

python class oop instance

No comments:

Post a Comment