Quirk difference between classes and functions

Steve Gronicus at SGA.Ninja
Tue Feb 26 16:48:33 EST 2019


I have been a silent reader on this and am interested in understanding more
about the scope of variables in Python.  They do not seem to behave as I
have experienced in other programming languages.

I have used functions in python but was not aware of class.
It would benefit me very well if someone could post a simple example of each
on which I might experiment.
Steve


----------------------------------------------------------------------------
----------------
Footnote:
There's 99 bugs in the code, in the code.
99 bugs in the code.
Take one down and patch it all around.
Now there's 117 bugs in the code.

-----Original Message-----
From: Python-list <python-list-bounces+gronicus=sga.ninja at python.org> On
Behalf Of Gregory Ewing
Sent: Tuesday, February 26, 2019 4:27 PM
To: python-list at python.org
Subject: Re: Quirk difference between classes and functions

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.

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
--
https://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list