Defining class methods outside of a Python class

I am trying to understand how class methods are called when defined externally. Although I found other topics dedicated to this problem, I did not find a very clear answer to my question, so I want to publish it in a simple form.

Defines a function outside the class and calls 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 

vs

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

and then calling him

 object = MyClass() object.function(arg) 

Thanks in advance.

+4
source share
1 answer

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

Note that there are no “class methods” in your code — both definitions lead to regular (sample) methods.

The definition of a function leads to the same functional object, regardless of whether it happens at the class or module level. Thus, the assignment in the first version of the code leads to the fact that the function object is placed in the class region, and as the second version, a completely equivalent class region is obtained.

+9
source

All Articles