Variable scope in classes
Robert Brewer
fumanchu at amor.org
Thu Mar 25 17:12:22 EST 2004
Larry Bates 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__?
>
> 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()
>
> returns the following traceback:
>
> Traceback (most recent call last):
> File
> "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scrip
> tutils.py",
> line 301, in RunScript
> exec codeObject in __main__.__dict__
> File "F:\SYSCON\SMARTROUTE\classjunk.py", line 13, in ?
> x=bar()
> File "F:\SYSCON\SMARTROUTE\classjunk.py", line 10, in __init__
> foo.__init__()
> File "F:\SYSCON\SMARTROUTE\classjunk.py", line 3, in __init__
> print self.__something
> AttributeError: bar instance has no attribute '_foo__something'
>
> Is there some "other" way to do this without passing information
> through foo.__init__ argument list?
The quick and easy way would be to name your "__something" variable in
such a way that it doesn't start with two underscores. Try "_something"
with one underscore if you want to avoid the name mangling. See
http://www.python.org/doc/current/ref/atom-identifiers.html for a
discussion of mangling if you're not familiar with it.
The other way would be to form the mangled name yourself.
class foo:
def __init__(self):
attr = "_" + self.__class__.__name__ + "__something"
print getattr(self, attr)
...or something like that.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list