Need help with Python scoping rules

kj no.email at please.post
Wed Aug 26 11:27:06 EDT 2009


In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks <pavlovevidence at gmail.com> writes:

>On Aug 26, 7:09=A0am, kj <no.em... at please.post> wrote:
>> In <16b72319-8023-471c-ba40-8025aa6d4... at a26g2000yqn.googlegroups.com> Ca=
>rl Banks <pavlovevide... at gmail.com> writes:
>>
>> >> First, one of the goals of OO is encapsulation, not only at the
>> >> level of instances, but also at the level of classes. =3DA0Your commen=
>t
>> >> suggests that Python does not fully support class-level encapsulation.
>> >I can't answer this, I don't even know what you are talking about.
>>
>> Yes, you do. =A0As I said in another post, Python offers some degree
>> of class-level encapsulation (e.g. class variables). =A0But it is
>> limited by the fact that these class-encapsulated elements can't
>> always be accessed from within the class itself, which is kind of
>> silly.

>Nope, you're wrong.  Class variables are accessible wherever a class
>exists.  The apparent silliness of this is because you are confusing
>classes with class statements.

Repeating an earlier example (though I've switched the order of
the two internal functions):

class Demo(object):
    def fact_iter(n):
        ret = 1
        for i in range(1, n + 1):
            ret *= i
        return ret

    def fact_rec(n):
        if n < 2:
            return 1
        else:
            return n * fact_rec(n - 1)

    classvar1 = fact_iter(5)
    classvar2 = fact_rec(5)


In the initialization of classvar1, fact_iter is invoked without
any problem even though the class is not yet created: no need to
qualify it with the name of the class.  This is completely inconsistent
with the requirement that fact_rec be so qualified when invoked
within fact_rec.

kynn



More information about the Python-list mailing list