unbound method must be called with instance as first argument - python

前端 未结 3 713
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 05:51

I keep on receiving the error: TypeError: unbound method get_num_students() must be called with Student instance as first argument (got nothing instead)

Her

3条回答
  •  天命终不由人
    2021-02-04 06:40

    It seems like you wanted to define grad_early, get_num_students and get_grad_2013 as class methods, but you declared them as instance methods instead.

    An instance method is a method that, well, belongs to an instance of the class.

    An example would be

    class Student(object):
        # ...
    
        def print_name(self):  # This is an instance method
            print "executing instance method"
    
        @classmethod
        def num_of_students(cls)
            print "executing class method"
    

    The difference is that an instance method will work on s = Student() s.print_name()

    And a class method will work on the class itself Student.

提交回复
热议问题