Need help with Python scoping rules

7stud bbxx789_05ss at yahoo.com
Wed Aug 26 15:28:28 CEST 2009


On Aug 25, 7:26 pm, Dave Angel <da... at ieee.org> wrote:
> 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.  
>

An "argument" is something that is specified in the the function
call.  I assume you are trying to state something like, "fact() is not
defined with a parameter variable named self".  However, that has
never been a requirement in python:


class A(object):

    def fact(n):
        print n

    fact("hello")


a = A()
a.fact()

--output:--
hello
<__main__.A object at 0x7faf0>






More information about the Python-list mailing list