我试过:
__all__ = ['SpamPublicClass']
但是,这当然只是为了:
from spammodule import *
有没有办法阻止类的导入。我担心有人会写我的代码的 API 级别的混淆:
from spammodule import SimilarSpamClass
它会导致调试混乱。
我试过:
__all__ = ['SpamPublicClass']
但是,这当然只是为了:
from spammodule import *
有没有办法阻止类的导入。我担心有人会写我的代码的 API 级别的混淆:
from spammodule import SimilarSpamClass
它会导致调试混乱。
约定是使用 _ 作为前缀:
class PublicClass(object):
pass
class _PrivateClass(object):
pass
以下:
from module import *
不会导入 _PrivateClass。
但这不会阻止他们导入它。他们仍然可以明确地导入它。
from module import _PrivateClass
私有类的名称以和下划线开头,以便仅通过名称就可以清楚地表明它不是供公共使用的。这实际上不会阻止任何人导入该类,但这不应该是偶然发生的。这是一个完善的约定,以下划线开头的名称是“内部的”。
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.