4

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.

asked Jul 20, 2012 at 15:32
1
  • 3
    These 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. Commented Jul 20, 2012 at 15:35

1 Answer 1

9

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.

answered Jul 20, 2012 at 15:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.