[英]How to structure public and private methods in python
假設我有一個 class 有幾個公共方法和幾個 _private 或“helper”方法。
在代碼中存在如何對它們進行排序的問題。 它可以是1.所有公共然后所有私有或2.調用公共函數之后的私有函數。 (請參閱最佳實踐:在 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()
優點:
functionx.helper1.helper12.helper121
_
僅用於輔助函數的定義_helperx
functionx.helpery
缺點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.