Quirk difference between classes and functions

jfong at ms4.hinet.net jfong at ms4.hinet.net
Tue Feb 26 20:16:56 EST 2019


Gregory Ewing at 2019/2/27 AM 5:26:49 wrote:
> Thomas Jollans wrote:
> > I imagine there's a justification for the difference in behaviour to do
> > with the fact that the body of a class is only ever executed once, while
> > the body of a function is executed multiple times.
> 
> I suspect there isn't any deep reason for it, rather it's just
> something that fell out of the implementation, in particular
> the decision to optimise local variable access in functions
> but not other scopes.
> 
> When compiling a function, the compiler needs to know which
> variables are local so that it can allocate slots for them in
> the stack frame. But when executing a class body, the locals
> are kept in a dict and are looked up dynamically.

If the compiler can do any decision on the variable's name, when it goes to line of print, how it handle it?

x = 0
def f():
    print(x)

def g():
    print(x)
    x = 1
    print(y)

--Jach

> The compiler *could* be made to treat class bodies the same
> way as functions in this regard, but it would be extra work
> for little or no benefit. Most code in class bodies just
> defines new names without referring to anything else in the
> same scope.
> 
> -- 
> Greg




More information about the Python-list mailing list