Python special declaration of non-local variables of the writing, for explanation!

in closure functions, nonlocal is generally used to declare non-local variables, for example:

def func1():
    num=0
    def iner():
        nonlocal num
        num+=1
        return num
    return iner
        
res1=func1()
print([res1(),res1(),res1(),res1()])-sharp[1,2,3,4]

but today I see another way to write it, which can achieve the same effect:

def func2():
    func2.num=0
    def iner():
        func2.num+=1
        return func2.num
    return iner 

res2=func2()
print([res2(),res2(),res2(),res2()]) -sharp[1,2,3,4]
 

like this, similar to defining class attributes, but using function names to declare non-local variables, I don"t understand.
is there a great god who can explain it?

Sep.16,2021

in a word, everything is an object, and so is a function.

Menu