Skip to main content
`Ctrl`+`K`

# Function and Method Objects

Everything is an object in Python, even functions and member functions.

    def my_function():
        print('Oh, you called me!')

    print(type(my_function))
    print(id(my_function))
    print(dir(my_function))

    <class 'function'>
    140438181160432
    ['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

    print(my_function.__name__)

    my_function

Member functions are bit special.

    class my_class:
        def some_method(self, some_string):
            print('You called me with {}'.format(some_string))

    my_object = my_class()

    print(type(my_object.some_method))
    print(type(my_class.some_method))

    <class 'method'>
    <class 'function'>

If the method `my_object.some_method` is called, then the Python interpreter inserts the owning object as first argument and calls the corresponding function `my_class.some_method`. In other words, the following two lines are equivalent:

    my_object.some_method('Hello')
    my_class.some_method(my_object, 'Hello')

    You called me with Hello
    You called me with Hello