Need help with Python scoping rules

Jan Kaliszewski zuo at chopin.edu.pl
Tue Aug 25 20:34:11 EDT 2009


25-08-2009 o 22:16:24 Stephen Hansen <apt.shansen at gmail.com> wrote:

> The OP's probably is that during the execution of the class body, the  
> class
> doesn't exist... so the 'def fact' -can't- use Classname.fact to address
> itself explicitly, and within fact the locals don't contain a reference  
> to
> the function itself, and its globals don't either. You just can't do  
> that.
> The right way, IMHO, is to move 'fact' up and out of the class into a  
> _fact global variable. Alternatively, you can use a metaclass.

Note that you can also pass a function to the function itself, and then
it works:

>>> class Foo:
...     def func(foo=None):
...         if foo:
...             return foo()
...         else:
...             return '2nd step'
...     x = func(func)
...
>>> Foo.x
'2nd step'

Note that when called from class definition body, func is an ordinary
function, not a method. It become a method *when it's called as a method*
(what is possible *after* creating the class => outside the definition).

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list