熱線電話:13121318867

登錄
首頁精彩閱讀牛大了,這代碼看著真專業
牛大了,這代碼看著真專業
2022-04-02
收藏
牛大了,這代碼看著真專業

作者:麥叔

來源:麥叔編程

引子

今年開始,我在翻譯一本大部頭的,比較經典的的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,類和方法都加了非常簡明扼要的文檔??雌饋砭秃芟駜戎脦斓拇a。
  • 函數都使用類型提示,增加代碼可讀性,可以使用mypy等做類型檢查。
  • __init__函數使用了默認值,確保每個初始化出的實例都有有效的屬性值。
  • reset函數沒有自己實現輪子,而是直接調用move方法。
  • 類的docstring中提供了使用例子,可以用doctest等測試工具做代碼的簡單自動化測試。

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢