[Tutor] (no subject)

Paul Sidorsky paulsid@shaw.ca
Wed, 06 Mar 2002 10:13:48 -0700


Henry Porter wrote:

> I'm wondering why with some functions I have to type the function then the
> variable I want that function to act on in parentheses after the function
> (e.g. len(a)) and other functions I have to type the variable then a
> period then the function (e.g. a.strip()).

The functions with the form obj.func() "belong" to the data type being
used.  strip() belongs to the string type, and a.strip() operates
exclusively on the variable called a in this case.

len() is a funtion that operates on any sequence data type as well as
those that provide a __len__ function, so it doesn't make much sense for
it to be attached to any single data type.  That's probably why it's a
builtin.

BTW if you've done any work with classes you'll have noticed that you
have to supply the "self" parameter to member functions.  This actually
gets passed the object in front of the period (a in your case).  So the
"internal call" to the function could be thought of as something like
this:  StringType.strip(a).  Python's syntax is just saving you some
typing.  On the inside they really aren't all that different.  :-)

> Sorry for this stupid beginner question, 

No such thing!

> but I'm trying to figure out a
> rhyme and reason for when to do which.

Chapter 2 of the Library Reference on the builtins can help answer this
question.  Pay particular attention to sections 2.1 and 2.2.6.  (2.2.8
is also important.)  Here's the link:

http://www.python.org/doc/current/lib/builtin.html

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/