Dive Into Python-Chapter 4. The Power Of Introspection
Số trang: 45
Loại file: pdf
Dung lượng: 0.00 B
Lượt xem: 7
Lượt tải: 0
Xem trước 5 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
Tham khảo tài liệu dive into python-chapter 4. the power of introspection, công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả
Nội dung trích xuất từ tài liệu:
Dive Into Python-Chapter 4. The Power Of IntrospectionChapter 4. The Power Of IntrospectionThis chapter covers one of Pythons strengths: introspection. As you know,everything in Python is an object, and introspection is code looking at othermodules and functions in memory as objects, getting information aboutthem, and manipulating them. Along the way, youll define functions with noname, call functions with arguments out of order, and reference functionswhose names you dont even know ahead of time.4.1. Diving InHere is a complete, working Python program. You should understand a gooddeal about it just by looking at it. The numbered lines illustrate conceptscovered in Chapter 2, Your First Python Program. Dont worry if the rest ofthe code looks intimidating; youll learn all about it throughout this chapter.Example 4.1. apihelper.pyIf you have not already done so, you can download this and other examplesused in this book.def info(object, spacing=10, collapse=1): Print methods and doc strings. Takes module, class, list, dictionary, orstring. 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 .join([%s %s % (method.ljust(spacing),processFunc(str(getattr(object, method).__doc__))) for method in methodList])if __name__ == __main__: print info.__doc__ This module has one function, info. According to its function declaration, it takes three parameters: object, spacing, and collapse. The last two are actually optional parameters, as youll see shortly. The info function has a multi-line doc string that succinctly describes the functions purpose. Note that no return value is mentioned; this function will be used solely for its effects, rather than its value. Code within the function is indented. The if __name__ trick allows this program do something useful when run by itself, without interfering with its use as a module for other programs. In this case, the program simply prints out the doc string of the info function. if statements use == for comparison, and parentheses are not required.The info function is designed to be used by you, the programmer, whileworking in the Python IDE. It takes any object that has functions or methods(like a module, which has functions, or a list, which has methods) and printsout the functions and their doc strings.Example 4.2. Sample Usage of apihelper.py>>> from apihelper import info>>> li = []>>> info(li)append L.append(object) -- append object to endcount L.count(value) -> integer -- returnnumber of occurrences of valueextend L.extend(list) -- extend list byappending list elementsindex L.index(value) -> integer -- returnindex of first occurrence of valueinsert L.insert(index, object) -- insert objectbefore indexpop L.pop([index]) -> item -- remove andreturn item at index (default last)remove L.remove(value) -- remove firstoccurrence of valuereverse L.reverse() -- reverse *IN PLACE*sort L.sort([cmpfunc]) -- sort *IN PLACE*; ifgiven, cmpfunc(x, y) -> -1, 0, 1By default the output is formatted to be easy to read. Multi-line docstrings are collapsed into a single long line, but this option can bechanged by specifying 0 for the collapse argument. If the function namesare longer than 10 characters, you can specify a larger value for thespacing argument to make the output easier to read.Example 4.3. Advanced Usage of apihelper.py>>> import odbchelper>>> info(odbchelper)buildConnectionString Build a connection stringfrom a dictionary Returns string.>>> info(odbchelper, 30)buildConnectionString Build a connectionstring from a dictionary Returns string.>>> info(odbchelper, 30, 0)buildConnectionString Build a connectionstring from a dictionary Returns string.4.2. Using Optional and Named ArgumentsPython allows function arguments to have default values; if the function iscalled without the argument, the argument gets its default value. Futhermore,arguments can be specified in any order by using named arguments. Storedprocedures in SQL Server Transact/SQL can do this, so if youre a SQLServer scripting guru, you can skim this part.Here is an example of info, a function with two optional arguments:def info(object, spacing=10, collapse=1):spacing and collapse are optional, because they have default valuesdefined. object is required, because it has no default value. If info iscalled with only one argument, spacing defaults to 10 and collapsedefaults to 1. If info is called ...
Nội dung trích xuất từ tài liệu:
Dive Into Python-Chapter 4. The Power Of IntrospectionChapter 4. The Power Of IntrospectionThis chapter covers one of Pythons strengths: introspection. As you know,everything in Python is an object, and introspection is code looking at othermodules and functions in memory as objects, getting information aboutthem, and manipulating them. Along the way, youll define functions with noname, call functions with arguments out of order, and reference functionswhose names you dont even know ahead of time.4.1. Diving InHere is a complete, working Python program. You should understand a gooddeal about it just by looking at it. The numbered lines illustrate conceptscovered in Chapter 2, Your First Python Program. Dont worry if the rest ofthe code looks intimidating; youll learn all about it throughout this chapter.Example 4.1. apihelper.pyIf you have not already done so, you can download this and other examplesused in this book.def info(object, spacing=10, collapse=1): Print methods and doc strings. Takes module, class, list, dictionary, orstring. 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 .join([%s %s % (method.ljust(spacing),processFunc(str(getattr(object, method).__doc__))) for method in methodList])if __name__ == __main__: print info.__doc__ This module has one function, info. According to its function declaration, it takes three parameters: object, spacing, and collapse. The last two are actually optional parameters, as youll see shortly. The info function has a multi-line doc string that succinctly describes the functions purpose. Note that no return value is mentioned; this function will be used solely for its effects, rather than its value. Code within the function is indented. The if __name__ trick allows this program do something useful when run by itself, without interfering with its use as a module for other programs. In this case, the program simply prints out the doc string of the info function. if statements use == for comparison, and parentheses are not required.The info function is designed to be used by you, the programmer, whileworking in the Python IDE. It takes any object that has functions or methods(like a module, which has functions, or a list, which has methods) and printsout the functions and their doc strings.Example 4.2. Sample Usage of apihelper.py>>> from apihelper import info>>> li = []>>> info(li)append L.append(object) -- append object to endcount L.count(value) -> integer -- returnnumber of occurrences of valueextend L.extend(list) -- extend list byappending list elementsindex L.index(value) -> integer -- returnindex of first occurrence of valueinsert L.insert(index, object) -- insert objectbefore indexpop L.pop([index]) -> item -- remove andreturn item at index (default last)remove L.remove(value) -- remove firstoccurrence of valuereverse L.reverse() -- reverse *IN PLACE*sort L.sort([cmpfunc]) -- sort *IN PLACE*; ifgiven, cmpfunc(x, y) -> -1, 0, 1By default the output is formatted to be easy to read. Multi-line docstrings are collapsed into a single long line, but this option can bechanged by specifying 0 for the collapse argument. If the function namesare longer than 10 characters, you can specify a larger value for thespacing argument to make the output easier to read.Example 4.3. Advanced Usage of apihelper.py>>> import odbchelper>>> info(odbchelper)buildConnectionString Build a connection stringfrom a dictionary Returns string.>>> info(odbchelper, 30)buildConnectionString Build a connectionstring from a dictionary Returns string.>>> info(odbchelper, 30, 0)buildConnectionString Build a connectionstring from a dictionary Returns string.4.2. Using Optional and Named ArgumentsPython allows function arguments to have default values; if the function iscalled without the argument, the argument gets its default value. Futhermore,arguments can be specified in any order by using named arguments. Storedprocedures in SQL Server Transact/SQL can do this, so if youre a SQLServer scripting guru, you can skim this part.Here is an example of info, a function with two optional arguments:def info(object, spacing=10, collapse=1):spacing and collapse are optional, because they have default valuesdefined. object is required, because it has no default value. If info iscalled with only one argument, spacing defaults to 10 and collapsedefaults to 1. If info is called ...
Tìm kiếm theo từ khóa liên quan:
thủ thuật máy tính công nghệ thông tin quản trị mạng tin học computer networkTài liệu liên quan:
-
52 trang 434 1 0
-
24 trang 359 1 0
-
Top 10 mẹo 'đơn giản nhưng hữu ích' trong nhiếp ảnh
11 trang 321 0 0 -
Làm việc với Read Only Domain Controllers
20 trang 312 0 0 -
74 trang 304 0 0
-
96 trang 299 0 0
-
Báo cáo thực tập thực tế: Nghiên cứu và xây dựng website bằng Wordpress
24 trang 291 0 0 -
Đồ án tốt nghiệp: Xây dựng ứng dụng di động android quản lý khách hàng cắt tóc
81 trang 286 0 0 -
EBay - Internet và câu chuyện thần kỳ: Phần 1
143 trang 277 0 0 -
Tài liệu hướng dẫn sử dụng thư điện tử tài nguyên và môi trường
72 trang 270 0 0