gpt4 book ai didi

python - Flask-PyMongo : how come "self._Collection__database"?

转载 作者:可可西里 更新时间:2023-11-01 10:34:48 24 4
gpt4 key购买 nike

在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com