0

I am reading the official python documentation on python classes here: https://docs.python.org/release/3.8.5/tutorial/classes.html?highlight=class.

In section 9.3.2, following an example of class definition

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

there is a remark:

So in our example, x.f is a valid method reference, since MyClass.f is a function, but x.i is not, since MyClass.i is not. But x.f is not the same thing as MyClass.f — it is a method object, not a function object.

I am a bit confused about the difference between a method object and a function object. To me they are both some object that can be called. After more reading, I think the difference is:

  • A function object must receive a full list of argument(s) as in its definition.
  • A method object receives some arguments implicitly, for example, the x.f method above, when called, receives the instance x implicitly as its first argument self.

I have some questions:

  • Is this the correct understanding of the difference between a method object and function object?
  • Is this the sole difference between them?
  • Are there any other, maybe more complicated, examples that illustrates the difference?
ihdv
  • 1,927
  • 2
  • 13
  • 29
  • 1
    Function objects are [*descriptors*](https://docs.python.org/3/howto/descriptor.html), their `__get__` methods return a method object, which basically just partially applied version of itself (with the instance as the first argument). So, `some_instance.some_method` invokes the descriptor protocol, the `__get__` method of the function is invoked, and `some_instance.some_method` is evaluated as that method object, so ehwn you do `some_isntance.some_method()` the method object is actually being called. Note, this happens every time, so `some_instance.some_method is not some_instace.some_method` – juanpa.arrivillaga Mar 29 '21 at 12:31
  • @juanpa.arrivillaga Thanks! This is very clear. One small thing, do you mean in the last sentence `some_instance.some_method` is not `some_class.some_method`? – ihdv Mar 29 '21 at 12:46

0 Answers0