ThisProgramIt's relatively complicated. Let's look at the program first.
Def Info (object, spacing = 10, collapse = 1): "" print methods and Doc strings. takes modules, class, list, Dictionary, or string. "methodlist = [method for method in Dir (object) If hasattr (getattr (object, method), '_ call _')] 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 _": Print (info. _ Doc __)
Here I have made some changes to adapt to the python 3 program.
Notes:
This global function callable is not supported in Python 3.
Callable ()
Global Function
In Python 2, you can check whether an object was callable (like a function) with the globalCallable()
Function. In Python 3, this global function has been eliminated. to check whether an object is callable, check for the existence of_ Call __()
Special method.
Python 2: callable (anything)
Python 3: hasattr (anything, '_ call __')
Understanding of this sentence
Processfunc = collapse and (lambda S: "". Join (S. Split () or (lamdba S: S)
Knowledge points:
1, and
In python, only the following values are false: 0, "", [], (), {}, and others are true. Therefore, the lambda function here is also true. When multiple and operations are performed together, if both are true, the last one is returned.
2. Split () function
Split () without parameters, it is split by blank space
Iii. Lambda Functions
Lambda functions are used to quickly define functions which are equivalent
Def f (x ):
Return x * 2
F (2)
This is equivalent:
G = Lambda X: x * 2
G (2)
Or (lambda X: x * 2) (2)
The role of processfunc is clearly understood now. If collapse is true, the string in processfunc (string) is compressed to a blank space. If collapse is false, the unchanged parameter is directly returned.
Explain the following sentence:
Print ("\ n ". join (["% S % s" % (method. ljust (spacing), processfunc (STR (getattr (object, method ). _ Doc _) for Method in methodlist])
There are several knowledge points:
1. Ljust () function
Fill the string with spaces to conform to the specified length
2. STR (getattr (object, method). _ Doc __)
If the method does not define the doc attribute, a none value is not obtained, but a none value can be obtained using the STR () method.
Before studying the next chapter, make sure that you can complete the following tasks without difficulty:
• Define and call functions with optional and named Parameters
• Use STR to forcibly convert any value to a string
• Use getattr to dynamically obtain the reference of functions and other attributes
• Extended list parsing syntax for list filtering
• Identify and-or skills and use them safely
• Define Lambda Functions
• Assign a function to a variable and call the function by referencing the variable.