You are here: Home > Dive Into Python > Getting To Know Python > Everything is an object | << >> | ||||
Dive Into PythonPython for experienced programmers |
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.
>>> import odbchelper >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> print odbchelper.buildConnectionString(params) server=mpilgrim;uid=sa;database=master;pwd=secret >>> print odbchelper.buildConnectionString.__doc__ Build a connection string from a dictionary Returns string.
import in Python is like require in Perl. Once you import a Python module, you access its functions with module.function; once you require a Perl module, you access its functions with module::function. |
Before we go any further, I want to briefly mention the library search path. Python looks in several places when you try to import a module. Specifically, it looks in all the directories defined in sys.path. This is just a list, and you can easily view it or modify it with standard list methods. (We’ll learn more about lists later in this chapter.)
>>> import sys >>> sys.path ['', '/usr/local/lib/python2.2', '/usr/local/lib/python2.2/plat-linux2', '/usr/local/lib/python2.2/lib-dynload', '/usr/local/lib/python2.2/site-packages', '/usr/local/lib/python2.2/site-packages/PIL', '/usr/local/lib/python2.2/site-packages/piddle'] >>> sys <module 'sys' (built-in)> >>> sys.path.append('/my/new/path')
Everything in Python is an object, and almost everything has attributes and methods.[1] All functions have a built-in attribute __doc__, which returns the doc string defined in the function’s source code. The sys module is an object which has (among other things) an attribute called path. And so forth.
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.
[1] Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this later in this chapter), and not all objects are subclassable (more on this in chapter 3). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in chapter 2).
<< Documenting functions |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | |
Indenting code >> |