Home  >  Q&A  >  body text

python2.7 - Execution order of python function or class code

The question has been modified. Let’s just look at Example 3

For simple control statements,

x = 1
if x > 0:
    print('true')
else:
    print('false')

We all know that when x > 0 is determined, the else statement will not be executed.

Python is an interpreted language. For functions, Example 1

# filename test.py

def test1():
    pass
    
# test1()

The following is my understanding that I don’t know whether it is correct or not:

1, for java, if the line of code test1() does not execute the call to function test1, then the entire program is basically meaningless, there will be no memory allocation, and there will be no execution
2. But for python, the test1 function object will be created, and then a series of operations in test1 will be saved. These operations will not be executed. Even if the entire program does not make any calls to test1, as long as the program does not end, then test1 will always exist in memory.
The reason is that after the program is run, the function test1 will become the attribute of the current module object, that is, module __main__ .
3. As for the function name 'test1', it refers to this function object, so even if the function is not called, the garbage collection mechanism will not recycle it

Nested functions Example 2

# filename test.py

def test1():
    def test2():
        pass
    # return test2()
    
# test1()

Regarding Example 1, is my understanding wrong?

What is the situation of the inner function test2 of test1 in Comparative Example 2? Is there any difference between the situation with and without the call?

The previous problem may not be described clearly, here is another example 3

>>> class A(object):
    a = []

    def test1(self):
        pass
    
    @classmethod
    def test2(cls):
        print('cls.a', sys.getrefcount(cls.a))
        print('cls.test1:', sys.getrefcount(cls.test1))

        
>>> A.test2()
('cls.a', 2)
('cls.test1:', 1)

The above output is 2, which is understandable, but why is the other one 1?

>>> def test3():
    def test4():
        pass

    
>>> sys.getrefcount(test3)
2
>>> dir(test3)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

# sys.getrefcount(test4)    NameError: name 'test4' is not defined

The current question is, is the inner function test4 in test3 in memory? If so, where? (I think it should be in the memory) If not, why is there no test4? If there is no test4, what should I do if I modify the above code?

def test3():
    def test4():
        pass
    return test4   # return test4()
When I just revised the question, I suddenly thought that it might not be of practical significance for programming. Everyone might know how to define and use inner functions. But I still hope someone can answer my question
習慣沉默習慣沉默2686 days ago754

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-06-12 09:27:49

    It is recommended to split this question into two different questions in the future.
    (1) This function is not called. Python has another memory management strategy, reference counting: "Principle: Record the number of times an object is referenced by other objects. When the reference to this object is removed, the reference count is also reduced. If it is reduced to 0, the object will be released." So I guess, it should have been recycled during reference counting.

    (2) Whether it is called depends on whether the reference of an object has been removed and whether there is a reference cycle. There is a similar discussion in the email discussion thread here. I don’t know if it answers your question.

    reply
    0
  • Cancelreply