Need help with Python scoping rules
bruno.42.desthuilliers at websiteburo.invalid
Thu Aug 27 10:49:24 CEST 2009
kj a écrit :
> In <jeqdncAMUYvTrwjXnZ2dnUVZ8ludnZ2d at bt.com> "Martin P. Hellwig" <martin.hellwig at dcuktec.org> writes:
>> kj wrote:
>>> First, one of the goals of OO is encapsulation, not only at the
>>> level of instances, but also at the level of classes.
>> Who says?
> Python itself: it already offers a limited form of class encapsulation
> (e.g. class variables).
"class variables" - which FWIW include the "methods" - are just
attributes of the class *object* (reminder : Python's classes and
functions *are* objects too). Any name bound at the top level of the
class statement scope becomes an attribute of the class object. IOW,
this "limited form of class encapsulation" is just the ordinary "form of
encapsulation" you'll get with Python objects.
> It would be nice if it went all the way
> and gave classes their own bona fide scope. (But I hasten to add:
> I *still* don't understand the Python scope model,
I think that what you should first understand are Python's execution and
>> Anyway, you could be right (I am not capable to judge it) and Python
>> should change on this issue but from what I gathered, Pythons OO is
>> inspired by the following:
>> - Don't repeat yourself
>> - Containing code into logical units makes it easier to understand and
> ...except, apparently, when that code is a recursive function, in
> which case one's out of luck.
I wrote quite a few recursive functions in Python and never had any
>>> Second, my example shows that Python puts some peculiar restrictions
>>> on recursion.
It's not a restriction on recursion, it's a scoping rule that apply to
any other name. You can't access the class statement's scope from within
a function, period.
>>> Recursion! One of the central concepts in the theory
>>> of functions!
>> It is also one of the best ways to shoot yourself in the foot...
> If recursion is so evil, and Python so intent in saving us from
> shooting ourselves in the foot, why does it allow recursion at all?
Recursion is not evil, and Python doesn't try to prevent anyone from
doing stupid things anyway. FWIW, do you know that you can add / replace
/ remove attributes (including methods) at runtime, both on a
per-instance or per-class basis ? And even dynamically change the class
of an object ?-)
More information about the Python-list