Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inheritance

Tags:

python

class

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?

like image 771
vks Avatar asked Dec 24 '22 20:12

vks


2 Answers

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.

like image 84
Andrew Guy Avatar answered Jan 08 '23 05:01

Andrew Guy


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

like image 36
Lucas Avatar answered Jan 08 '23 03:01

Lucas