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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With