Python:如何禁止从模块导入类?

发布于 2024-08-19 17:02:29 字数 268 浏览 7 评论 0原文

我尝试过:

__all__ = ['SpamPublicClass']

但是,当然这只是为了:

from spammodule import *

有没有办法阻止类的导入。我担心有人会编写我的代码的 API 级别的混乱:

from spammodule import SimilarSpamClass

这会导致调试混乱。

I tried:

__all__ = ['SpamPublicClass']

But, of course that's just for:

from spammodule import *

Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write:

from spammodule import SimilarSpamClass

and it'll cause debugging mayhem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尹雨沫 2024-08-26 17:02:30

约定是使用 _ 作为前缀:

class PublicClass(object):
    pass

class _PrivateClass(object):
    pass

如下:

from module import *

不会导入 _PrivateClass。

但这不会阻止他们进口它。他们仍然可以显式导入它。

from module import _PrivateClass

The convention is to use a _ as a prefix:

class PublicClass(object):
    pass

class _PrivateClass(object):
    pass

The following:

from module import *

Will not import the _PrivateClass.

But this will not prevent them from importing it. They could still import it explicitly.

from module import _PrivateClass
贪恋 2024-08-26 17:02:30

私有类的名称以 和 下划线开头,这样通过名称就可以清楚地表明它不供公共使用。这实际上不会阻止任何人导入该类,但它不应该偶然发生。这是一个公认的约定,以下划线开头的名称是“内部”的。

Start the names of private classes with and underscore, so that it will be clear just by the name that it is not for public use. That will not actually prevent anybody from importing the class, but it shouldn't happen by accident. It's a well established convention that names starting with an underscore are "internal".

×眷恋的温暖 2024-08-26 17:02:30

在 Python 中,没有办法真正阻止对模块内容或类内容的访问。 此类事情按惯例处理将您的类命名为_SimilarSpamClass(带有前导下划线),以向调用者表明这是您模块的实现细节,而不是模块的一部分发布的API。

在 Python 中将某些内容标记为“私有”正确记录您的公共 API,以便其他开发人员知道如何正确使用您的模块并遵循标准命名约定,以便模块的用户很容易注意到他们何时偏离了 API 并转向了实现。

There is no way to actually block access to the contents of a module or the contents of a class for that matter in Python. This sort of thing is handled by convention name your class _SimilarSpamClass (with a leading underscore) to indicate to callers that this is an implementation detail of your module and not part of the published API.

To mark something as "private" in Python properly document your public API so other developers know how to use your module correctly and follow the standard naming conventions so that users of your module easily notice when they have strayed from your API to your implementation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文