Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining class methods outside of the class Python

I am trying to understand how the methods of the class are called when defined from outside of it. While I've found other threads addressing this issue, I haven't found a very clear answer to my question, so I want to post it in a simple form.

Is defining a function outside of a class and calling it from the inside the same as defining it from the inside.

def my_func(self_class, arg):
    do something with arg
    return something

class MyClass:
    function = my_func

versus

class MyClass:
    def function(self, arg):
        do something with arg
        return something

and then calling it as

object = MyClass()
object.function(arg)

Thank you in advance.

like image 487
Diego-MX Avatar asked Jan 17 '23 01:01

Diego-MX


1 Answers

The two versions are completely equivalent (except that the first version also introduces my_func into the global namespace, of course, and the different name you used for the first parameter).

Note that there are no "class methods" in your code – both definitions result in regular (instance) methods.

A function definition results in the same function object regardless of whether it occurs at class or module level. Therefore, the assignment in the first version of the code lifts the function object into the class scope, and results in a completely equivalent class scope as the second version.

like image 128
Sven Marnach Avatar answered Jan 28 '23 23:01

Sven Marnach