学习Python的利器:内置函数dir()和help()

(1)内置函数dir()用来查看对象的成员。在Python中所有的一切都是对象,除了整数、实数、复数、字符串、列表、元组、字典、集合等等,还有range对象、enumerate对象、zip对象、filter对象、map对象等等,函数也是对象,类也是对象,模块也是对象。这样的话,dir()的用武之地就大了。

>>> dir(3) #查看整数类型的成员,这里省略了输出结果

>>> dir('a') #查看字符串类型的成员

>>> import math >>> dir(math) #查看math模块的成员

>>> def demo():pass #定义一个空函数

>>> dir(demo) #查看函数的成员

>>> class Demo: #定义一个类 def __init__(self):pass def methodA(self):pass def methodB(self):pass

>>> dir(Demo) #查看类的成员 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'methodA', 'methodB'] >>> d = Demo() #实例化一个对象 >>> dir(d) #查看对象成员 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'methodA', 'methodB']

(2)内置函数help()用来返回对象的帮助信息,尤其常用来查看函数或对象方法的帮助信息。除此之外,help()还可以做很多事,例如查看模块的帮助信息,以及Python关键字和运算符的信息。

>>> help(sum) #查看内置函数的帮助文档 Help on built-in function sum in module builtins:

sum(iterable, start=0, /) Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.

>>> help(3) #查看整数类型的帮助文档 Help on int object:

class int(object) | int(x=0) -> integer | int(x, base=10) -> integer

...(其他输出结果略去)

>>> help('math') #查看标准库的帮助文档,注意要加引号 Help on built-in module math:

NAME math

DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard.

...(其他输出结果略去)

>>> help('') #查看字符串类型的帮助文档 Help on class str in module builtins:

class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str

...(其他输出结果略去)

>>> import math >>> help(math.sin) #查看标准库函数的帮助文档 Help on built-in function sin in module math:

sin(...) sin(x) Return the sine of x (measured in radians).

>>> help() #进入帮助环境

Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam".

help>

>>> help('in') #查看Python关键字的帮助文档 Membership test operations **************************

The operators "in" and "not in" test for membership. "x in s" evaluates to true if *x* is a member of *s*, and false otherwise. "x not in s" returns the negation of "x in s". All built-in sequences and set types support this as well as dictionary, for which "in" tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression "x in y" is equivalent to "any(x is e or x == e for e in y)".

...(其他输出结果略去)

>>> help('with') #查看Python关键字with的帮助文档 The "with" statement ********************

The "with" statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common "try"..."except"..."finally" usage patterns to be encapsulated for convenient reuse.

with_stmt ::= "with" with_item ("," with_item)* ":" suite with_item ::= expression ["as" target]

...(其他输出结果略去)

>>> help('for') #查看Python关键字for的帮助文档 The "for" statement *******************

The "for" statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]

...(其他输出结果略去)

>>> help('+') #查看所有运算符的帮助文档 Operator precedence *******************

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

...(其他输出结果略去)

那么问题来了,如果我们自己设计了函数或类或模块,如何能够通过help()给出帮助文档呢?答案是写注释。

>>> def add(x, y): #定义函数,编写注释 '''Accept integers x and y, return x+y''' return x+y

>>> help(add) #查看自定义函数的帮助文档 Help on function add in module __main__:

add(x, y) Accept integers x and y, return x+y

>>> class T: '''This is a test.''' pass

>>> help(T) #查看自定义类的帮助文档 Help on class T in module __main__:

class T(builtins.object) | This is a test. | | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)

原文发布于微信公众号 - Python小屋(Python_xiaowu)

原文发表时间:2017-02-17

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏个人随笔

论 Java 的访问权限

Java中成员访问权限 Java中的访问权限控制符有四个: 作用域_____当前类____同一package___子孙类____其他package publi...

3948
来自专栏青玉伏案

窥探Swift编程之错误处理与异常抛出

在Swift 2.0版本中,Swift语言对其错误处理进行了新的设计,当然了,重新设计后的结果使得该错误处理系统用起来更爽。今天博客的主题就是系统的搞一下Swi...

2045
来自专栏Java帮帮-微信公众号-技术文章全总结

Java面试系列8

? 一、heap和stack有什么区别 栈是一种线形集合,其添加和删除元素的操作应在同一段完成。 栈按照后进先出的方式进行处理。 堆是栈的一个组成元素 ...

3155
来自专栏软件测试经验与教训

上期答案

3405
来自专栏源哥的专栏

XML文件解析

在现在很多采用java开发的基于b/s结构的系统中,经常将一些配置参加放到一个xml文件中,然后在这个文件中取参数,这样减少了hard code的情况。下面这个...

922
来自专栏Young Dreamer

简易前端模板引擎

模板解析 解决的问题: 将data和js+html片段解析成html片段,完成赋值和js逻辑,如下所示: 输入: var data = {     name: ...

21710
来自专栏Python小屋

Python 3.x中内置函数range()函数的用法

range()是Python开发中非常常用的一个内置函数,语法格式为range([start,] end [, step] ),有range(stop)、ran...

3274
来自专栏*坤的Blog

属性文件读写测试 PropertiesFileTest

1748
来自专栏jessetalks

Javascript基础回顾 之(二) 作用域

参数传递的问题   在Javascript中所有的参数传递都是按值传递的。也就是说把函数外部的值复制给函数内部的参数,就和把值从一个变量复制到另一个变量一样。...

2846
来自专栏轮子工厂

一篇文章帮你解决中文乱码问题---JavaWeb中文编码问题全面解析

这就是为什么我们在浏览器的地址栏中能看到中文,但是把地址拷贝出来后中文就变成了一些奇怪的串了。

7694

扫码关注云+社区

领取腾讯云代金券