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

标签 python mongodb flask

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

相关文章:

python - 如何在 python 中显示非英文字符?

javascript - MongoDB 元素顺序

python - BuildError : Could not build url for endpoint 'user' with values ['nickname' ]. 您是否忘记指定值 ['page' 、 'username' ]?

MongoDB 外壳 : How to convert array fields into string

javascript - 在html中将滚动条位置设置到底部

flask - Jinja2/Flask 动态变量名更改

python - 将字符串编码为八进制 utf-8 Python 3

python - Python any 的传递生成器与列表

python - Keras 输入形状 ValueError

node.js - Mongoose 具有不同对象方法的多类型模式