相关疑难解决方法(0)

有人可以在Python中解释__all__吗?

我越来越多地使用Python,并且我一直__all__在不同的__init__.py文件中看到变量集.有人可以解释这是做什么的吗?

python syntax namespaces

873
推荐指数
10
解决办法
26万
查看次数

使用装饰器向__all__添加名称是一个好习惯吗?

这是Python中的一个好习惯(来自Active State Recipes - Public Decorator)吗?

import sys

def public(f):
  """Use a decorator to avoid retyping function/class names.

  * Based on an idea by Duncan Booth:
  http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a
  * Improved via a suggestion by Dave Angel:
  http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8a42e1
  """
  all = sys.modules[f.__module__].__dict__.setdefault('__all__', [])
  if f.__name__ not in all:  # Prevent duplicates if run from an IDE.
      all.append(f.__name__)
  return f

public(public)  # Emulate decorating ourself
Run Code Online (Sandbox Code Playgroud)

一般的想法是定义一个装饰器,它接受一个函数或类,并将其名称添加到__all__当前模块的名称.

python coding-style

20
推荐指数
2
解决办法
3263
查看次数

标签 统计

python ×2

coding-style ×1

namespaces ×1

syntax ×1