pymongo为什么我们可以使用点来获取集合实例?

时间:2016-07-19 11:38:18

标签: python pymongo

from pymongo import MongoClient
DBC = MongoClient("localhost").test.test

正如上面的代码段一样,我们只能使用.代替get_database("test")get_collection("test")来获取数据库实例或集合实例。尽管方便,但我想知道是什么让这个语法糖发生了?

1 个答案:

答案 0 :(得分:2)

发生__getattr__() magic method点符号/属性查找。

让我们看看源代码。 MongoClientdefines __getaattr__方法并按名称实例化Database类:

def __getattr__(self, name):
    """Get a database by name.
    Raises :class:`~pymongo.errors.InvalidName` if an invalid
    database name is used.
    :Parameters:
      - `name`: the name of the database to get
    """
    if name.startswith('_'):
        raise AttributeError(
            "MongoClient has no attribute %r. To access the %s"
            " database, use client[%r]." % (name, name, name))
    return self.__getitem__(name)

def __getitem__(self, name):
    """Get a database by name.
    Raises :class:`~pymongo.errors.InvalidName` if an invalid
    database name is used.
    :Parameters:
      - `name`: the name of the database to get
    """
    return database.Database(self, name)

same goes for the Database class