TypeError: missing 1 required positional argument: 'self' but the class is instanciated

Question:

I am trying to write a Zoo program but I always get the following output:

Traceback (most recent call last):
  File "C:Dokumente und Einstellungencisco_2zoo.py", line 31, in <module>
    ape.vorstellen()
  File "C:Dokumente und Einstellungencisco_2zoo.py", line 26, in vorstellen
    Tier.vorstellen()
TypeError: vorstellen() missing 1 required positional argument: 'self'

Here is the source code:

class Zoo:

    def __init__(self,name,rasse):
        self.name = name
        self.rasse = rasse

    def vorstellen (self):
        print ("Hallo, Ich heisse {0} und bin ein {1}".format(self.name,self.rasse))

class Tier (Zoo):

    def __init__(self,name,rasse,kafig):
        Zoo.__init__(self,name, rasse)
        self.kafig = kafig
    def vorstellen (self):
        Zoo.vorstellen()
        print ("Ich wohne in Kaefig {0}".format(self.kafig))

class Affe (Tier):

    def __init__(self,name,rasse,kafig,futter):
        Tier.__init__(self,name,rasse,kafig)
        self.futter = futter

    def vorstellen(self):
        Tier.vorstellen()
        print ("Ich fresse {0}".format(self.futter))

ape = Affe("Chimp","Affe",3,"Bananen")

ape.vorstellen()

Does anyone have an idea why I’m getting that error?

Asked By: Sulumar

||

Answers:

You are calling the unbound method on the parent class:

def vorstellen(self):
    Tier.vorstellen()
    print ("Ich fresse {0}".format(self.futter))

Add in self there:

def vorstellen(self):
    Tier.vorstellen(self)
    print ("Ich fresse {0}".format(self.futter))

or use super() to load the next method in the hierarchy; super() binds the method for you:

def vorstellen(self):
    super().vorstellen()
    print ("Ich fresse {0}".format(self.futter))

This assumes you are using Python 3; in Python 2, Zoo must inherit from object and you must pass in the current class (by name) and self to super():

def vorstellen(self):
    super(Affe, self).vorstellen()
    print ("Ich fresse {0}".format(self.futter))

Inheriting from object makes the Zoo class and all subclasses new-style classes. This is the default in Python 3.

Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.