TypeError: unbound method…instance as first argume

2020-04-21 04:29发布

问题:

Ok, one TypeError more. Here is my code:

class musssein:      
  def notwendig(self, name):
    self.name = name
    all = []                # fuer jede Eigenschaft eine extra Liste
    day = []
    time = []
    prize = []
    what = []
    kategorie = []
    with open(name) as f:
        for line in f:
            data = line.replace('\n','') #Umbruchzeichen ersetzen
            if data != ' ':             # immer nur bis zur neuen Zeile bzw. bis zum ' ' lesen
                all.append(data)        # in liste einfuegen
            else:
                kategorie.append(all.pop())
                what.append(all.pop())
                prize.append(all.pop())
                time.append(all.pop())
                day.append(all.pop())

def anzeige():
     musssein.notwendig('schreiben.txt')
     print table.Table(
        table.Column('Datum', day),
        table.Column('Kategorie', kategorie),
        table.Column('Was?', what),
        table.Column('Preis', prize, align=table.ALIGN.LEFT))

The description is in german, but it explain me just what you probably already know.

When I run now anzeige(), the terminal shows me only:

File "test.py", line 42, in anzeige musssein.notwendig('schreiben.txt') TypeError: unbound method notwendig() must be called with musssein instance as first argument (got str instance instead)

I tried many possibilities and read a lot of other threads, but I didn't find the right one which explained it.

回答1:

Your method "notwendig" expects to have an instance of musssein as its first parameter, this gets done transparently if it is called on an instance of musssein rather than on the class itself:

newinstance=musssein()
newinstance.notwendig('schreiben.txt')

is equivalent to

newinstance=musssein()
musssein.notwendig(newinstance,'schreiben.txt')

Also, your code doesn't actually store the information from the file other than in local variables which are destroyed as soon as the method exits. You need to change your method to:

def notwendig(self, name):
    self.name = name
    self.all = []                # fuer jede Eigenschaft eine extra Liste
    self.day = []
    self.time = []
    self.prize = []
    self.what = []
    self.kategorie = []

in the next function "anzeige" they will need to be changed to newinstance.day, newinstance.kategorie etc otherwise you'll get an undefined global variable error



回答2:

You must create (instantiate) an object of the class mussein before calling its method

def anzeige():
    my_var = mussein()
    my_var.notwendig('schreiben.txt')

So the self parameter of the notwendig method is my_var (an instance of mussein).

By the way, usually the class names must start with a capital letter. So in this case it should be Mussein.