zoukankan      html  css  js  c++  java
  • 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 著

  • 相关阅读:
    SRF 认证
    Python getattr
    jQueryattr()与prop()之间的区别
    鼠标事件(拖拽)
    Python中操作MySQL的模块---pymsql
    C++ 存储类
    C++ 修饰符类型
    C++ 变量作用域
    C++ 变量类型
    C++ 数据类型
  • 原文地址:https://www.cnblogs.com/anovana/p/8134179.html
Copyright © 2011-2022 走看看