diveintopython.org
Python for experienced programmers

 

1.4. Everything is an object

In case you missed it, I just said that Python functions have attributes, and that those attributes are available at runtime.

A function, like everything else in Python, is an object.

Example 1.5. Accessing the buildConnectionString function's doc string

>>> import odbchelper                              1
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> print odbchelper.buildConnectionString(params) 2
server=mpilgrim;uid=sa;database=master;pwd=secret
>>> print odbchelper.buildConnectionString.__doc__ 3
Build a connection string from a dictionary

Returns string.
1 The first line imports the odbchelper program as a module. Once you import a module, you can reference any of its public functions, classes, or attributes. Modules can do this to access functionality in other modules, and you can do it in the IDE too. This is an important concept, and we'll talk more about it later.
2 When you want to use functions defined in imported modules, you have to include the module name. So you can't just say buildConnectionString, it has to be odbchelper.buildConnectionString. If you've used classes in Java, this should feel vaguely familiar.
3 Instead of calling the function like you would expect to, we asked for one of the function's attributes, __doc__.

Everything in Python is an object, so everything can have attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code.

This is so important that I'm going to repeat it in case you missed it the first few times: everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects, as we'll see shortly.