代码注释是代码可读性的很重要的保障,在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()则会将所有的字符串文档都检索出来