簡體   English   中英

python中如何構造公有和私有方法

[英]How to structure public and private methods in python

假設我有一個 class 有幾個公共方法和幾個 _private 或“helper”方法。

在代碼中存在如何對它們進行排序的問題。 它可以是1.所有公共然后所有私有或2.調用公共函數之后的私有函數。 (請參閱最佳實踐:在 class 定義中對公共/受保護/私有進行排序?

另一種方法是嵌套私有函數,但會產生運行時開銷。

如何構造代碼以便輕松查看:

  • class的接口
  • 函數的邏輯結構?

這是我自己的答案,但我很高興看到其他選擇。

我將使用函數而不是方法來展示它,當然這同樣適用於方法。

我的方法是創建一個裝飾器:

#  helper.py

def helper(func):
    def decorator(helper):
        helper.__name__ = '{func.__name__}.{helper,__name__}'

ant 然后像這樣使用它:

from helper import helper 

# interface {

def public_func():
    public_func.helper1()
    public_func.helper2()

def if_the_function_has_a_long_name_you_can():
    this = if_the_function_has_a_long_name_you_can
    ...
    this.helper3()


# interface }


# private {

@helper(public_func)
def _helper1():
    print('helper1')


@helper(public_func)
def _helper2():
    print('helper2')
    _helper2.nested_helper()


@helper(if_the_function_has_a_long_name_you_can)
def _helper3():
    print('helper3')


@helper(_helper2)
def _nested_helper():
    print('nested')


# private }



def not_polite():
    public_func.helper1()
    public_func.helper2.nested_helper() 

優點:

  • 代碼結構扁平,函數內部沒有類和函數
  • 仍然有結構,但僅用作文檔
  • 您可以創建任意嵌套的虛擬結構,甚至無需創建 class 或嵌套函數。 該結構僅由點名表示: functionx.helper1.helper12.helper121
  • 調試更容易,因為您只看到 function 名稱的調用順序!
  • 下划線_僅用於輔助函數的定義
  • 很容易看出什么是輔助函數以及它們服務於哪些 function。
  • 輔助函數可以從任何地方調用,甚至可以從模塊外部調用,(雖然不禮貌)
  • 輔助函數仍然可以通過其原始名稱_helperx
  • 但是將出現在回溯中的助手 function 的名稱具有點綴樣式functionx.helpery

缺點

  • 添加輔助函數作為公共函數的屬性會混淆 IDE 的代碼分析,因此您沒有點線樣式的代碼完成。
  • 您有以下編碼開銷:
    • 導入裝飾器
    • 裝飾幫手
  • 任何其他?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM