作者:麦叔
来源:麦叔编程
引子今年开始,我在翻译一本大部头的,比较经典的的Python进阶书籍。
有空就翻译几页。这本书不仅是教你很多进阶的Python的语法,更重要的是讲解很多设计方法和设计思想。
这些方法和思想,一点点叠加起来,就会让你从一个普通的程序员变成一个很专业的程序员。至少看起来挺唬人的!
昨天我在翻译关于docstring的章节。书中举的一个例子,把一个很普通的类,转变成了跟Python内置的库一样专业的代码。
我感觉眼睛一亮,觉得有必要跟大家分享一下。
设计需求这个类的功能很简单:
- 类名Point,代表二维坐标系中的一个点。
- 属性:x和y代表二维坐标
- 方法:类包含3个方法,实现了“回到原点”,“移动到指点的点”,“计算两个点之间的距离”。
想想看,你会怎么写呢?
专业级的代码我就直接分享我认为比较专业的代码吧,请仔细阅读,品味其中专业的地方:
- class Point: """
- Represents a point in two-dimensional geometric coordinates
- >>> p_0 = Point()
- >>> p_1 = Point(3, 4)
- >>> p_0.calculate_distance(p_1)
- 5.0
- """ def __init__(self, x: float = 0, y: float = 0) -> None: """
- 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.
- :param x: float x-coordinate
- :param y: float x-coordinate
- """ self.move(x, y) def move(self, x: float, y: float) -> None: """
- Move the point to a new location in 2D space.
- :param x: float x-coordinate
- :param y: float x-coordinate
- """ self.x = x
- self.y = y def reset(self) -> None: """
- Reset the point back to the geometric origin: 0, 0
- """ self.move(0, 0) def calculate_distance(self, other: "Point") -> float: """
- Calculate the Euclidean distance from this point
- to a second point passed as a parameter.
- :param other: Point instance
- :return: float distance
- """ return math.hypot(self.x - other.x, self.y - other.y)
来说一下,为什么我觉得这段代码是专业级的:
- 类名和方法名都非常直观,简单易懂。有没有?
- 通过docstring,类和方法都加了非常简明扼要的文档。看起来就很像内置库的代码。
- 函数都使用类型提示,增加代码可读性,可以使用mypy等做类型检查。
- __init__函数使用了默认值,确保每个初始化出的实例都有有效的属性值。
- reset函数没有自己实现轮子,而是直接调用move方法。
- 类的docstring中提供了使用例子,可以用doctest等测试工具做代码的简单自动化测试。
相关帖子DA内容精选
|


雷达卡





京公网安备 11010802022788号







