Jackal
Jackal

Reputation: 23

Calling a function within my class isn't working

class MyClass(object):
    def f(self):
        return 'hello world'

Everything i have been reading here and on other websites that with this code, if i run MyClass.f() it should return with hello world but instead i keep getting

Traceback (most recent call last):
  File "C:\Users\Calvin\Desktop\CS_Semester_Project\testing.py", line 5, in <module>
    MyClass.f()
TypeError: unbound method f() must be called with MyClass instance as first argument (got nothing instead)

I have no idea what i'm doing wrong, any help would be very appreciated.

Upvotes: 2

Views: 887

Answers (2)

Michael Francis
Michael Francis

Reputation: 8747

The error is telling you that f() must be called on an instance of type MyClass, not on MyClass itself.

You need to create an instance of MyClass:

obj = MyClass()

In this case obj would be an instance of MyClass.

Then you need to call f() on that object:

obj.f()

The error message is confusing because of the way that methods are called in Python. When you call obj.f(), obj is implicitly passed to f() as the first argument. That's why you have to write

def f(self):
    ...

self is going to refer to obj when you call obj.f().

Knowing that, if you take another look at the error message:

TypeError: unbound method f() must be called with MyClass instance as first argument (got nothing instead)

It makes more sense. It says that f() was expecting an argument, (specifically an instance of MyClass) and didn't get one because tried to call it on a type rather than an instance of a type.

Upvotes: 2

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29113

Do this:

myCls = MyClass()
myCls.f()

As error saying you f method require instance while you calling it like a static function You can read more about python classes in tutorial in methods section

Upvotes: 2

Related Questions