python 文档小结

代码注释是代码可读性的很重要的保障,在python中代码注释规则以及如何获得这些注释以理解代码作用都是学好python很重要的保障。
实例参见 test.py 如下代码

#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
filename: test.py
this file is used for explain how to write code explain for other and yourself.
"""
class ABC(object):
    """this is a class for test"""

    def __init__(self,name):
        # class constructor
        self.name=name

    def go(self):
        """print attribute for class ABC"""
        print (self.name)

在test.py文件所在目录运行python shell进入python解释器然后

>>>import test

dir()

python内置函数dir()是抓取对象内可用所有属性列表的简单方式。如对象的方法以及较简单的数据项。可以帮助我们了解对象都有哪些可用的属性和方法。
比如我们运行

>>>a=ABC('pcf')
>>>dir(ABC)
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'go']
 >>>dir(a)
 ['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'go',
 'name']    # dir(ABC)比dir(a)少一个name属性,想想就知道为嘛了            

注释和__doc__

python注释有两种方式,一种是 # 注释,这种注释是给’内部人’ 看的,不会被help(),__doc__这些工具给找出来。还有一种是字符串注释,这种注释要放在模块文件、函数以及类语句的顶端,在任何可执行代码前面。python会自动封装这些字符串成为所谓的字符串文档,使其具有相应对象的__doc__属性,可被help()和__doc__ 检索出来
每个py文件,每个类,每个函数都有__doc__属性。如下

>>>ABC.__doc__
'this is a class for test'
>>>ABC.__init__.__doc__

>>>ABC.go.__doc__
'print attribute for class ABC'

help()函数和__doc__差不多都是检索字符串文档,只不过help()检索出来的是文件\类对象\函数下的所有字符串文档。而__doc__则只检索一层,比如在ABC.__doc__没有检索该类下方法的字符串文档。而help()则会将所有的字符串文档都检索出来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值