Class scoping problem...

Simon Brunning SBrunning at trisystems.co.uk
Tue Sep 26 12:25:54 EDT 2000


I'm having a bit of a problem with scoping within a class. Something similar
is mentioned in Andrew Kuchling's 'Python Warts' page, but I can't find a
workaround.

Take the following:

class Foo:

    def __init__(self):
        self.bar = 1

    def baz(self):

        def quix():
            return self.bar

        return quix()

foo = Foo()

print foo.baz()

Running this, I get this:

Traceback (most recent call last):
  File "H:\SBrunning\Python\ClassScope.py", line 15, in ?
    print foo.baz()
  File "H:\SBrunning\Python\ClassScope.py", line 11, in baz
    return quix()
  File "H:\SBrunning\Python\ClassScope.py", line 9, in quix
    return self.bar
NameError: There is no variable named 'self'

Which is fair enough, 'cos self.bar isn't in the global namespace, and nor
is it in baz's namespace. But what do I *do*?

BTW, what I *can't* do is pass self.bar as an argument, 'cos in the real
case I'm defining a function to pass to a re.sub.

I-used-foo-so-Tim-won't-help-ly-yrs,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk

P.S. The usual apology for the legal tripe.




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.




More information about the Python-list mailing list