Tài liệu Dive Into Python-Chapter 4. The Power Of Introspection - Pdf 87

Chapter 4. The Power Of Introspection
This chapter covers one of Python's strengths: introspection. As you know,
everything in Python is an object, and introspection is code looking at other
modules and functions in memory as objects, getting information about
them, and manipulating them. Along the way, you'll define functions with no
name, call functions with arguments out of order, and reference functions
whose names you don't even know ahead of time.
4.1. Diving In
Here is a complete, working Python program. You should understand a good
deal about it just by looking at it. The numbered lines illustrate concepts
covered in Chapter 2, Your First Python Program. Don't worry if the rest of
the code looks intimidating; you'll learn all about it throughout this chapter.
Example 4.1. apihelper.py
If you have not already done so, you can download this and other examples
used in this book.
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.

Takes module, class, list, dictionary, or
string."""
methodList = [method for method in dir(object)
if callable(getattr(object, method))]
processFunc = collapse and (lambda s: "
".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),

processFunc(str(getattr(object, method).__doc__)))
for method in methodList])

if __name__ == "__main__":

extend L.extend(list) -- extend list by
appending list elements
index L.index(value) -> integer -- return
index of first occurrence of value
insert L.insert(index, object) -- insert object
before index
pop L.pop([index]) -> item -- remove and
return item at index (default last)
remove L.remove(value) -- remove first
occurrence of value
reverse L.reverse() -- reverse *IN PLACE*
sort L.sort([cmpfunc]) -- sort *IN PLACE*; if
given, cmpfunc(x, y) -> -1, 0, 1
By default the output is formatted to be easy to read. Multi-line doc
strings are collapsed into a single long line, but this option can be
changed by specifying 0 for the collapse argument. If the function names
are longer than 10 characters, you can specify a larger value for the
spacing argument to make the output easier to read.
Example 4.3. Advanced Usage of apihelper.py
>>> import odbchelper
>>> info(odbchelper)
buildConnectionString Build a connection string
from a dictionary Returns string.
>>> info(odbchelper, 30)
buildConnectionString Build a connection
string from a dictionary Returns string.
>>> info(odbchelper, 30, 0)
buildConnectionString Build a connection
string from a dictionary


its value. spacing still gets its default value of 10.

Even required arguments (like object, which has no default value) can
be named, and named arguments can appear in any order.
This looks totally whacked until you realize that arguments are simply a
dictionary. The “normal” method of calling functions without argument
names is actually just a shorthand where Python matches up the values with
the argument names in the order they're specified in the function declaration.
And most of the time, you'll call functions the “normal” way, but you always
have the additional flexibility if you need it.

The only thing you need to do to call a function is specify a value
(somehow) for each required argument; the manner and order in which
you do that is up to you.
Further Reading on Optional Arguments
 Python Tutorial discusses exactly when and how default arguments
are evaluated, which matters when the default value is a list or an
expression with side effects.
4.3. Using type, str, dir, and Other Built-In Functions
Python has a small set of extremely useful built-in functions. All other
functions are partitioned off into modules. This was actually a conscious
design decision, to keep the core language from getting bloated like other
scripting languages (cough cough, Visual Basic).
4.3.1. The type Function
The type function returns the datatype of any arbitrary object. The possible
types are listed in the types module. This is useful for helper functions that
can handle several types of data.
Example 4.5. Introducing type
>>> type(1)
<type 'int'>

>>> str(horsemen)
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper)
"<module 'odbchelper' from
'c:\\docbook\\dip\\py\\odbchelper.py'>"
>>> str(None)
'None'

For simple datatypes like integers, you would expect str to work,
because almost every language has a function to convert an integer to a
string.

However, str works on any object of any type. Here it works on a list
which you've constructed in bits and pieces.

str also works on modules. Note that the string representation of the
module includes the pathname of the module on disk, so yours will be
different.

A subtle but important behavior of str is that it works on None, the
Python null value. It returns the string 'None'. You'll use this to your
advantage in the info function, as you'll see shortly.
At the heart of the info function is the powerful dir function. dir returns
a list of the attributes and methods of any object: modules, functions, strings,
lists, dictionaries... pretty much anything.
Example 4.7. Introducing dir
>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']

>>> string.join
<function join at 00C55A7C>
>>> callable(string.punctuation)
False
>>> callable(string.join)
True
>>> print string.join.__doc__
join(list [,sep]) -> string

Return a string composed of the words in list,
with
intervening occurrences of sep. The default
separator is a
single space.

(joinfields and join are synonymous)

The functions in the string module are deprecated (although many
people still use the join function), but the module contains a lot of useful
constants like this string.punctuation, which contains all the
standard punctuation characters.

string.join is a function that joins a list of strings.

string.punctuation is not callable; it is a string. (A string does
have callable methods, but the string itself is not callable.)

string.join is callable; it's a function that takes two arguments.

Any callable object may have a doc string. By using the callable

failed.
IOError I/O operation failed.

[...snip...]

Python comes with excellent reference manuals, which you should
peruse thoroughly to learn all the modules Python has to offer. But
unlike most languages, where you would find yourself referring back to
the manuals or man pages to remind yourself how to use these modules,
Python is largely self-documenting.
Further Reading on Built-In Functions
 Python Library Reference documents all the built-in functions and all
the built-in exceptions.
4.4. Getting Object References With getattr
You already know that Python functions are objects. What you don't know is
that you can get a reference to a function without knowing its name until
run-time, by using the getattr function.
Example 4.10. Introducing getattr
>>> li = ["Larry", "Curly"]
>>> li.pop
<built-in method pop of list object at 010DF884>
>>> getattr(li, "pop")
<built-in method pop of list object at 010DF884>
>>> getattr(li, "append")("Moe")
>>> li
["Larry", "Curly", "Moe"]
>>> getattr({}, "clear")
<built-in method clear of dictionary object at
00F113D4>
>>> getattr((), "pop")


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status