ehsan shirzadi
ehsan shirzadi

Reputation: 4859

unbound method MyFunction() must be called with Tools instance as first argument (got nothing instead)

When I'm trying to call my function from my class this error raised. This is my class:

class Tools:
    def PrintException(self):
        # Do something
        return 'ok'

View.py:

from tools import Tools

def err(request):
    a = 10
    b = 0
    msg = ""
    try:
        print a / b
    except Exception,ex:
        c = Tools
    return HttpResponse(Tools.PrintException())

I've tried to search and have found many articles about this error but I think none of them are my problem!
unbound method must be called with instance as first argument (got nothing instead)
unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Upvotes: 0

Views: 3255

Answers (2)

kylieCatt
kylieCatt

Reputation: 11039

To use your method without an instance of a class you can attach a class method decorator like so:

class Tool:
    @classmethod
    def PrintException(cls):
        return 'ok'

can be used:

>>> Tool.PrintException()
'ok'
>>> 

Upvotes: 2

BartoszKP
BartoszKP

Reputation: 35891

What you assign to c is a class, not an instance of a class. You should do:

c = Tools()

Further, you should call the method on the instance:

def err(request):
    a = 10
    b = 0
    msg = ""
    try:
        print a / b
    except Exception,ex:
        c = Tools()
        return HttpResponse(c.PrintException())

Note, that I've changed the indentation so the return statement is executed only on exception. This is the only way I can think of to make some sense out of it - it is unclear what are you trying to achieve exactly with your Tools class. This name is too generic - it doesn't tell anything about the purpose of this class.

Upvotes: 3

Related Questions