作者:麦叔
来源:麦叔编程
今年开始,我在翻译一本大部头的,比较经典的的Python进阶书籍。
有空就翻译几页。这本书不仅是教你很多进阶的Python的语法,更重要的是讲解很多设计方法和设计思想。
这些方法和思想,一点点叠加起来,就会让你从一个普通的程序员变成一个很专业的程序员。至少看起来挺唬人的!
昨天我在翻译关于docstring的章节。书中举的一个例子,把一个很普通的类,转变成了跟Python内置的库一样专业的代码。
我感觉眼睛一亮,觉得有必要跟大家分享一下。
这个类的功能很简单:
想想看,你会怎么写呢?
我就直接分享我认为比较专业的代码吧,请仔细阅读,品味其中专业的地方:
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)
来说一下,为什么我觉得这段代码是专业级的:
数据分析咨询请扫描二维码