python - 将实例命名为与模块相同的名称是否可以?

标签 python namespaces python-import

我经常发现用小写命名包含类定义的模块和该类的实例,并使用驼峰命名为类名是“自然的”。例如,我想这样做:

In [2]: from publisher import Publisher

In [3]: publisher = Publisher()

这里我有一个名为 publisher 的模块, 也是 Publisher 的一个实例以同样的方式调用。似乎模块和实例都按预期“工作”:
In [4]: from publisher import RandomData

In [5]: publisher.random.uuid()
Out[5]: 'c490508d-2071-536e-2f38-4b03b04351e1'

我从模块中导入了另一个类并调用了一个实例方法。无论我是指模块还是实例,Python 是否“从上下文中理解”?以这种方式重复使用名称可以吗?

最佳答案

你没有隐藏任何东西,这里没有重用任何名字。姓名 publisher在您使用 publisher = Publisher() 创建该实例之前,您的命名空间中并未使用该实例。 .如果您尝试使用名称 publisher紧跟在 from publisher import Publisher 之后行,你会得到一个 NameError异常(exception)。

那是因为 from <module> import <name>表单只集<name>在您的命名空间中。在哪里都没关系<name>是从进口的;您绝不会收到 <module>命名空间中的名称。

换句话说,from publisher import Publisher声明基本上翻译为:

if 'publisher' not in sys.modules:
    # find and load the publisher module
    # sys.modules['publisher'] = newly_loaded_module
Publisher = sys.modules['publisher'].Publisher  # set the Publisher global

除了名字sys永远不会在您的命名空间中设置,Python 只是访问 sys.modules直接内部。

所以,从技术角度来看:不,这完全没问题。

您可能会发现,将模块名称用于实例变量可能会混淆该名称对您的代码的 future 读者(如果不是 Python)的引用。

你可能也把这个混淆了
import publisher
publisher = publisher.Publisher()

这可能会影响模块。线路import publisher设置全局名称 publisher ,并在下一行替换 publisher带有新的对象引用。

铸成同sys.modules语言,你会这样做:
if 'publisher' not in sys.modules:
    # find and load the publisher module
    # sys.modules['publisher'] = newly_loaded_module
publisher = sys.modules['publisher']  # set the publisher global
publisher = publisher.Publisher()     # set the publisher global to something else

这也很好,除非您期望 publisher.Publisher()稍后会再次工作。 publisher不再引用该模块,因此可能会导致问题。这对于人类读者来说更令人困惑。

关于python - 将实例命名为与模块相同的名称是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40527733/

相关文章:

python - 在Python中使用YouTube API按相关性排序

python - 未绑定(bind)的变量和名称

variables - LESS:将带有变量的规则集(或 mixin)传递给另一个 mixin 并能够使用这些变量

c# - 使用 XmlDocument.CreateElement() 创建具有命名空间的 XML 元素

python - 如何使 Python 模块的 __init__.py 将其 help() 委托(delegate)给同级文件?

python - 如何避免导入 basemap 时出现 PROJ_LIB 错误?

Python-Turtle - 通过按住某个键来移动 turtle : releasing the key moves the turtle back instead of stopping it

python - Tkinter 窗口位于右下角

python - 无法在 Windows 7 中安装图形工具

python - 在 Python 中覆盖命名空间