[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: newbie question
From: "David C. Ullrich" <dullrich () sprynet ! com>
Date: 2008-12-02 17:13:21
Message-ID: dullrich-C75669.11132102122008 () text ! giganews ! com
[Download RAW message or body]
In article
<f2fd606a-d92b-434f-932e-fbf24e929d5b@h5g2000yqh.googlegroups.com>,
Nan <nan.li.g@gmail.com> wrote:
> Hello,
> I just started to use Python. I wrote the following code and
> expected 'main' would be called.
>
> def main():
> print "hello"
>
> main
>
> But I was wrong. I have to use 'main()' to invoke main. The python
> interpreter does not give any warnings for the above code. Is there
> any way/tool to easily detect this kind of errors ?
It's valid Python - it's only an error because it doesn't
do what you want.
The reason you're required to include the parentheses with
a function call is that in Python there are _other_ things
you might want to do with a function other than call it.
For example you can pass a function as a parameter to another
function. Silly example:
def twice(f):
f()
f()
def main():
print 'hello'
twice(main)
Before trying it, figure out what would happen if you said
twice(main()) .
A slightly more interesting example: twice(f) simply calls
f twice. double(f) returns a new function; when you call that
new function it calls f twice:
def double(f):
def res():
f()
f()
return res
def main():
print 'hello'
The point being that this example shows how sometimes you
want those parentheses and sometimes you don't. Either one
of the following is a way to call main twice:
mainmain = double(main)
mainmain()
or
double(main)()
When I said mainmain = double(main) I left off the
final parentheses because I didn't want to call mainmain
just then, I just wanted to set mainmain to the right thing.
> Thanks !
--
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic