In Python, I\'m trying to run a method in a class and I get an error:
Traceback (most recent call last):
File \"C:\\Users\\domenico\\Desktop\\py\\main.py\"
>>> class C:
... def f(self):
... print "hi"
...
>>> C.f()
Traceback (most recent call last):
File "", line 1, in
TypeError: unbound method f() must be called with C instance as
first argument (got nothing instead)
It fails because of TypeError because you didn't instantiate the class first, you have two choices: 1: either make the method static so you can run it in a static way, or 2: instantiate your class so you have an instance to grab onto, to run the method.
It looks like you want to run the method in a static way, do this:
>>> class C:
... @staticmethod
... def f():
... print "hi"
...
>>> C.f()
hi
Or, what you probably meant is to use the instantiated instance like this:
>>> class C:
... def f(self):
... print "hi"
...
>>> c1 = C()
>>> c1.f()
hi
>>> C().f()
hi
If this confuses you, ask these questions: