Need help with Python scoping rules

kj no.email at please.post
Wed Aug 26 16:58:10 CEST 2009


In <mailman.415.1251250004.2854.python-list at python.org> Dave Angel <davea at ieee.org> writes:

>Stephen Fairchild wrote:
>> You are trying to run code in a class that does not exist yet. 
>>
>> def Demo():
>>     def fact(n):
>>         if n < 2:
>>             return 1
>>         else:
>>             return n * fact(n - 1)
>>     return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar":
>> fact(5)})
>> Demo = Demo()
>>
>> d = Demo()
>> print d._classvar    # prints 120
>> print d.fact(7)      # prints 5040
>> print Demo           # prints <class '__main__.Demo'>
>>
>>   
>In all these messages, something I haven't seen pointed out is that 
>fact() has no self argument.  Seems to me that makes it a staticmethod, 
>so it should be declared that way.

No, the fact() function here represents an internal "helper"
function.  It is meant to be called only once to help initialize
a class variable that would be inconvenient to initialize otherwise;
this helper function is not meant to be called from outside the
class statement.  Granted, in the example I gave, the "helper"
function (factorial) is a bit silly, but that was just intended as
a simple and familiar example of a recursive function.  The actual
function that motivated this post would be considerably more
difficult to explain and would have obscured the point of the post.

kynn



More information about the Python-list mailing list