【问题标题】:How to structure public and private methods in python如何在python中构造公共和私有方法
【发布时间】:2023-01-23 00:13:49
【问题描述】:

假设我有一个包含多个公共方法和几个_private 或“helper”方法的类。

在代码中存在如何对它们进行排序的问题。它可能是1.所有公共然后所有私人或2.调用公共函数之后的私有函数。 (见Best practice: ordering of public/protected/private within the class definition?

另一种方法是嵌套私有函数,但会产生运行时开销。

如何构造代码以便轻松查看:

  • 类的接口
  • 函数的逻辑结构?

【问题讨论】:

    标签: 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 的代码分析,因此您没有点线样式的代码完成。
    • 您的编码开销为:
      • 导入装饰器
      • 装饰帮手
    • 还有其他吗?

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 2011-02-08
      • 1970-01-01
      • 2013-05-16
      • 2010-10-13
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2020-05-16
      相关资源
      最近更新 更多