在 Flask-PyMongo 中,它们使用 self._Collection__database
来表示此 Collection 对象所属的数据库对象:
class Collection(collection.Collection):
"""Custom sub-class of :class:`pymongo.collection.Collection` which
adds Flask-specific helper methods.
"""
def __getattr__(self, name):
attr = super(Collection, self).__getattr__(name)
if isinstance(attr, collection.Collection):
db = self._Collection__database
return Collection(db, attr.name)
return attr
为什么self._Collection__database
不是self.__database
?
test <a>and <i>
最佳答案
Flask-PyMongo 并不是随意选择这个名称。
该名称是 name mangling 的结果:
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, where classname is the current class name with leading underscore(s) stripped.
在 the parent-class definition ,该属性被定义为 self.__database ,并且 Python 会“修改”该名称(为 self._ClassName__attributename ),以便任何子类都不会用自己的赋值来覆盖自己的名称self.__database
属性。
关于python - Flask-PyMongo : how come "self._Collection__database"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9857895/