为一堆静态方法提供命名空间的最佳实践是什么?

Jin*_*Niu 1 python static-methods python-pattern

我需要一个模块内的命名空间,用于许多不同的静态方法做类似的工作。从我的研究中我了解到,在 Python 编程中,拥有一个充满静态方法的类被认为是反模式:

class StatisticsBundle:
  @staticmethod
  def do_statistics1(params):
     pass

  @staticmethod
  def do_statistics2(params):
     pass
Run Code Online (Sandbox Code Playgroud)

如果这不是一个好的解决方案,那么最好的做法是允许我getattr(SomeNameSpace, func_name)在同一个模块中进行命名空间查找吗?

Eli*_*jah 6

使用一个包。将函数放在单独的模块中,而不使用类。

在您计算机上的统计文件夹中定义 2 个模块:

  1. helpers.py 在哪里定义辅助函数。
  2. __init__.py 您编写大部分代码的地方。

helpers如果您可以为您在其中定义的函数组想出更好的名称,则可以重命名该模块。但是,__init__包的模块是特殊的。当包被导入时,__init__模块被赋予包名并被评估。

要应用您的示例:

#statistics\helpers.py

def do_statistics1(params):
     pass

def do_statistics2(params):
     pass

# Rest of module omitted
Run Code Online (Sandbox Code Playgroud)
#statistics\__init__.py
# Relative import
from . import helpers
# Get function using getattr()
do_statistics1 = getattr(helpers, "do_statistics1")
# Get function using dot notation
do_statistics2 = helpers.do_statistics2

# Rest of module omitted
Run Code Online (Sandbox Code Playgroud)

请务必通过导入来测试该包。评估包中的模块时,相对导入不起作用。

总之,您可以像从类中一样从模块中获取属性。

  • 包是一个带有子模块的模块。helpers.py 是statistics/__init__.py 的子模块。所以可以这么说,helpers.py 文件位于“现有的 stats/__init__.py 内部”。 (2认同)