unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

前端 未结 8 1808
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 23:42

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\"         


        
8条回答
  •  孤街浪徒
    2020-11-28 23:50

    How to reproduce this error with as few lines as possible:

    >>> 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:

    1. What is the difference between the behavior of a static method vs the behavior of a normal method?
    2. What does it mean to instantiate a class?
    3. Differences between how static methods are run vs normal methods.
    4. Differences between class and object.

提交回复
热议问题