4

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?

asked Feb 21, 2017 at 5:09
1
  • 2
    All statements in a class are executed when loading the class, e.g. class A: print('hello') would print "hello" when loading the class. Both @A.eat and A.eat() are executed statements when the class is loaded, even without the print A.a you would get the first 2 printed outputs. Commented Feb 21, 2017 at 5:15

2 Answers 2

5

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.

answered Feb 21, 2017 at 5:20
Sign up to request clarification or add additional context in comments.

Comments

5

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

answered Feb 21, 2017 at 5:14

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.