Pyhton对象解释

时间:2024-04-06 20:35:36

python的docstring提供了对每一个类、函数、方法的解释,在他们的定义下面可以有一行Python的标准字符串,该行字符串需要和下面的代码一样的缩进

docstring可以用单引号(')或者双信号(")标注的Pyhton字符串,如果多行的话,可以使用(''')或者(""")标注起来。docstring应该要能准确总结出它所描述的类或者对象的用途,应该能解释用法不那么明确的参数,并且也包含如何使用这些API的例子。

如下使用了Point类来展示docstring的用法:

class Point:
'Represents a point in two-dimensional geometric coordinates' def __init__(self, x = 0, y = 0):
'''Initialize the position of a new point, The x and y
coordinates can be specified. If they are not, the point
defaults to the origin.'''
self.move(x, y) def move(self, x, y):
"Move the point to a new location in two-dimensional space"
self.x = x
self.y = y def reset(self):
'Reset the point back to the geometric origin: 0,0'
self.move(0, 0) def calcalate_distance(self, other_point):
"""Calculate the distance from this point to a second point
passed as a parameter. This function uses the Pythagorean Theorem to calculate
the distance between the two points. The distance is returned
as a float."""
return math.sqrt(
(self.x - other_point.x)**2 +
(self.y - other_point.y)**2)

将上述的脚本保存为filename.py,然后使用python -i filename.py加载到交互解释器,然后在python的提示符里面输入help(Point),回车,可以看到漂亮的格式解释文档,如下

Pyhton对象解释

参考:

1、《Python3 面向对象编程》 [加]Dusty Philips 著