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.
-
3These aren't class methods, they are instance methods. You can do something similar with the class itself to add class methods, as you can to an instance to add instance methods to just one instance.Silas Ray– Silas Ray2012年07月20日 15:35:55 +00:00Commented Jul 20, 2012 at 15:35
1 Answer 1
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.