Class inheritance

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 it to A.abe empty, since we did not even create the object. How is the function added here 2? What exactly calls times eatto call 2?

+4
source share
2 answers

Because the class definition is an executable statement .

Any code inside the class body (but outside the function definitions) will be executed at runtime.

If you want to have code that runs only when you instantiate the class object, put it in the class method __init__.

, , , , :

- .

.

+5

, .

, , apple A.eat, (apple).

Python : https://docs.python.org/2/reference/executionmodel.html

+5

Source: https://habr.com/ru/post/1670360/


All Articles