Need help with Python scoping rules

Martin P. Hellwig martin.hellwig at dcuktec.org
Tue Aug 25 12:09:09 EDT 2009


kj wrote:
<cut>
> 
> Here's a toy example illustrating what I mean.  It's a simplification
> of a real-life coding situation, in which I need to initialize a
> "private" class variable by using a recursive helper function.

eh?

> 
> class Demo(object):
>     def fact(n):
>         if n < 2:
>             return 1
>         else:
>             return n * fact(n - 1)
> 
>     _classvar = fact(5)
> 
<cut>
Sorry still doesn't make sense, I'll give it a try though:

class Demo(object):
     """Apparently a 'real-life coding situation'"""
     def __init__(self):
         # Look at http://docs.python.org/tutorial/classes.html
         # for init explanation.
         self.__class_var = self.fact(5)

     def fact(self, number):
         """Look at http://docs.python.org/tutorial/classes.html why you 
need
         self."""
         if number < 2:
             return(1)
         else:
             return_value = number * self.fact(number -1)
             return(return_value)


TEST = Demo()
# Print the 'private' class variable
print(TEST._Demo__class_var)

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'



More information about the Python-list mailing list