syntax questions
Philippe Gendreau
philippe.gendreau at savoirfairelinux.com
Wed Jul 24 17:01:14 EDT 2002
* Michael Chermside <mcherm at destiny.com> [2002-07-24 14:16]:
> > I know about the dir() function, but I'm surprised that my list object
> > hides a function object (even if they have the same name).
> > Is that how python treats names all the time? Does it mean you can't
> > have a class, def and variable of the same name?
>
> Yes, that's how it works all the time.
>
> Actually, the ADVANTAGE of this is that you aren't required to memorize
> the entire list of all built-in functions and things. For instance, if
> you NEVER, EVER use the "input" function (as well you shouldn't), then
> it's not going to hurt you if you use a line like:
>
> for input in sys.stdin:
> process(input)
>
> Of course, it's still not a good idea, but you aren't forced to memorize
> the list of built-in stuff, nor does old code break when a new built-in
> function is added (which happens rarely, but does happen).
>
> As for having a class, a "def" (ie, function), and a variable all with
> the same name, no... not in the same namespace. And this is good.
> Because in Python (unlike some languages), a function, a class, and a
> "variable", are all objects, and can be used interchangably.
>
> Consider the map() function. It is normally passed a function as its
> first argument and applies it to the items in a list:
>
> >>> def add5(x):
> return x + 5
> >>> map( add5, range(4) )
> [5, 6, 7, 8]
>
> But classes are instantiated by calling them, as if they were functions.
> So we can pass a class in, where it expects a function, and it all works
> just fine:
>
> >>> from UserString import UserString
> >>> map( UserString, range(4) )
> ['0', '1', '2', '3']
>
> We could even use a variable to store the item to pass... resulting in
> code like this:
>
> >>> f1 = add5
> >>> f2 = UserString
> >>> [ map(f, range(4)) for f in f1, f2]
> [[5, 6, 7, 8], ['0', '1', '2', '3']]
>
> So the fact that all things are just "objects" and don't have separate
> namespaces is highly useful, since it comes closer to making
> "everything" first class objects, giving the language more power.
Thanks it makes sense, I see where it can be useful.
I think I'm gonna like python...
--
Philippe Gendreau
More information about the Python-list
mailing list