Joy of Python
This is true to some extent. Methods are associated with the instance of the object of which they are a part. When you see
def some_func(self, foo, bar)
Passing self is sometimes implicit when you call, for example:
obj.some_func(foo_val, bar_val)
Which is equal (it is assumed that obj has a class MyClass ) to
MyClass.some_func(obj, foo_val, bar_val)
Since the method is bound to obj , the argument self populated. This is part of Python, explicit with what it means. In other languages, this just appears in scope, and Python discovers how this happens.
You can also pass methods and manually pass them self when not called from the associated context.
Python docs do a good job :
xf = xf while True: print xf()
will continue to print hello world until the end of time.
What exactly happens when a method is called? You may have noticed that xf () was called> without the argument above, although the function definition for f () specified the argument>. What happened to the argument? Of course, Python throws an exception when the> function requiring an argument is called without any - even if the argument is not actually used ...
Actually, you may have guessed the answer: a special thing about methods is that the> object is passed as the first argument to the function. In our example, calling xf () is exactly equivalent to MyClass.f (x). In the general case, calling a method with a list of n arguments> is equivalent to calling a corresponding function with a created list of arguments> by inserting a method object before the first argument.
Aiden bell
source share