【问题标题】:How to structure public and private methods in python如何在python中构造公共和私有方法
【发布时间】:2023-01-23 00:13:49
【问题描述】:
标签:
oop
design-patterns
private
public
pyton
【解决方案1】:
这是我自己的答案,但我很高兴看到其他选择。
我将使用函数而不是方法来展示它,当然这同样适用于方法。
我的方法是创建一个装饰器:
# helper.py
def helper(func):
def decorator(helper):
helper.__name__ = '{func.__name__}.{helper,__name__}'
蚂蚁然后像这样使用它:
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()
not_polite()
优点:
- 代码结构扁平,函数内部没有类和函数
- 仍然有结构,但仅用作文档
- 您可以创建任意嵌套虚拟结构甚至无需创建类或嵌套函数。结构仅由点名表示:
functionx.helper1.helper12.helper121
- 调试更容易,因为您只看到函数名称的调用顺序!
- 下划线
_ 仅用于辅助函数的定义
- 很容易看出辅助函数是什么以及它们服务于哪些函数。
- 辅助函数可以从任何地方调用,甚至可以从模块外部调用,(虽然不礼貌)
- 辅助函数仍然可以通过其原始名称调用
_helperx
- 但是会出现在回溯中的辅助函数的名称具有带点的样式
functionx.helpery
缺点
- 将辅助函数添加为公共函数的属性会混淆 IDE 的代码分析,因此您没有点线样式的代码完成。
- 您的编码开销为:
- 还有其他吗?