Every chapter of Dive Into Python starts with an example. This example basically runs through this chapter to explain the knowledge points, but also use the knowledge points told by the previous chapter, such examples are for beginners. Nice.
APIHELPER.PY
DEF INFO (Object, spacing = 10, collapse = 1):
"" "Print Methods and Doc Strings.
Takes Module, Class, List, Dictionay, 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"% (spacing),
ProcessFunc (STR (GetAttr (Object, Method) .__ doc__)))))))
for method in methodlist])
IF __NAME__ == "__main__":
Print info .__ DOC__
Default Value
There are three parameters in the function in this example, and the latter two have default value, this and C Function is very similar, but there are different places, in python, call this function, the location of the parameters is not necessarily this order, such as , You can call info this (spacing = 30, object = apihelper)
2. And & or OR
This is also explained by three small examples.
>>> a = "first"
>>> b = "second"
>>> 1 And A OR B
'First'
>>> 0 and A OR B
'Second'
>>> a = ""
>>> b = "second"
>>> 1 And A OR B
'Second'
>>> a = ""
>>> b = "second"
>>> (1 and [a] or [b]) [0]
'' '
The original text on the book (the pieces of the red font come from the book)
WHEN USING AND, VALUES ARE Evaluated in a boolean context from left to right. 0, '', [], (),}, and none are false in a boolean context; everything else is true. Well, Almost Everything. By DEFAULT, INSTANCES OF CLASSES Are True In A Boolean Context, But You Can Define Special Methods in Your Class To Make An Instance Evaluate To False.
3. Filtering Lists
[Method for Method in Dir (Object) if Callable (Getattr (Object, Method)]
Key words are bold
The key to look for the format 4. Dir & Getattr
Dir Returns a list of the attributes and methods of any Object: Modules, Functions, Strings, Lists, Dictionaries ... pretty much anything.
Getattr Returns a Reference to a Function (Method) of any Object: Modules, strings, lists, dictionaries ... pretty much.
(I took the N_n written above, the bold place is the parameters of GetAttr.)
5. Callable
...............
6. Lambda S
This is a "simplified" Function! The format is: Lambda S: Expression of S
Its return value is the result of Expression of S.
It can give it ASSIGN to a variable, such as: g = lambda s: s.Split (), then G is a function that is parameter in s.
7. Str
STR turns the type of non-String type into string type, such as:
1-> '
1'
[] -> "[]"
None -> 'None'
The reason why the Str is used in the example is because some Function's DOC STRING may not, then return NONE. The use% s is displayed, indicating that it is necessary to decorate the String type, and use STR to do decoration. It is not afraid of NONE!
After understanding these, is it easy to understand?