Pyhton对象解释

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),回车,可以看到漂亮的格式解释文档,如下

 

参考:

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

转载于:https://www.cnblogs.com/anovana/p/8134179.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值