Difference between a library and a module...

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Mar 8 01:13:24 CET 2006


akameswaran at gmail.com a écrit :
> I'm not 100% sure what is a library in python.

Technically, nothing.

> 
> string.replace() I'm 90% sure is a function in the string module.
it is.

> However something like this:
> foo = "bar"
> foo.Capitalize()

s/C/c/

> bar.capitalize is a method.

...which is usually built from a function.

> 
> Read some intro to OOP, for a better understanding, but the main
> difference between a function and a method, is that a method is
> associated with some class or object.

Note that (part of) this association is made at runtime. Before you try 
to access it, it's a function (usually defined in the namespace of the 
class). When you try to access it, it's wrapped into a MethodWrapper 
object, that turns it into a method.

>  In Python it's really only
> objects (even class is an object)  Hence when I created the string
> object foo, and executed capitalize() it was a method on the string
> object. the same thing as a function might look something like:
> 
> # defining a function
> def capitalize(inStr)
>   #do stuff  here to capitalize the string
     outStr = inStr[0].upper() + intStr[1:].lower()
>   return outStr
> 
> foo = capitalize("bar")

Defining a method is really just defining a function:

 >>> class StringWrapper(str): pass
...
 >>> s = StringWrapper('foo')
 >>> s
'foo'
 >>> def capitalize(s):
...     print "yaoo, I was just a function,"
...           "I'll be promoted to a method"
...     try:
...             return s[0].upper() + s[1:].lower()
...     except (IndexError, AttributeError, TypeError), e:
...             return "too bad, could not capitlize %s : %s" % (s, e)
...
 >>> StringWrapper.capitalize = capitalize
 >>> s.capitalize()
yaoo, I was just a function, I'll be promoted to a method
'Foo'
 >>>



More information about the Python-list mailing list