Consider the following code:
class A(object):
a = []
@classmethod
def eat(cls, func):
print "called", func
cls.a.append(func)
class B(A):
@A.eat
def apple(self, x):
print x
A.eat(lambda x: x + 1)
print A.a
Output :
called <function apple at 0x1048fba28>
called <function <lambda> at 0x1048fbaa0>
[<function apple at 0x1048fba28>, <function <lambda> at 0x1048fbaa0>]
I expected A.a
to be empty as we have not even created an object.How are the 2
function getting added here?What exactly is causing eat
to get called 2
times?
Because a class definition is an executable statement.
Any code within the body of the class (but outside of function definitions) will be executed at run-time.
If you want to have code that only runs whenever a class object is instantiated, put it in the __init__
class method.
Note that some tutorials get this wrong, which no doubt adds to the confusion:
No code is run when you define a class - you are simply making functions and variables.
This is simply wrong.
The class body definition is executed when the module is imported.
And that also means the decorator is executed as well, passing the apple
function object to A.eat
and then binding the return value to the name of the function you passed (apple
).
You can read more about Python's execution model here: https://docs.python.org/2/reference/executionmodel.html
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