Variable scope in classes

Glenn Andreas gandreas at no.reply
Thu Mar 25 17:54:16 EST 2004


In article <P6OdnbAHb-yjyv7dRVn-uA at comcast.com>,
 "Larry Bates" <lbates at swamisoft.com> wrote:

> I'm confused about variable scope in a class
> that is derived from a base class framework.
> 
> Can someone enlighten me on why bar.__init__
> method can't see self.__something variable
> in the foo.__init__?
> 

Because __something is "private" to bar, and thus not visible anywhere 
else (unless you manually tweak on the "_foo", which is tricky and 
really not very nice).

> Example:
> 
> 
> class foo:
>     def __init__(self):
>         print self.__something
> 
> 
> class bar(foo):
>     __something="This is a test"
> 
>     def __init__(self):
>         foo.__init__(self)
> 
> 
> x=bar()

If you get rid of the private underscore:

class foo:
    def __init__(self):
        print self.something


class bar(foo):
    something="This is a test"

    def __init__(self):
        foo.__init__(self)


x = bar()

it works fine.



More information about the Python-list mailing list