Skip to main content
 首页 » 编程设计

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

2024年10月17日35jillzhang

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

就像上面的代码片段一样,我们可以只使用 . 而不是 get_database("test") 和 get_collection("test") 获取数据库实例或集合实例。尽管很方便,但我想知道是什么让这种语法糖发生了?

请您参考如下方法:

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

让我们看看源代码。 MongoClient 类 defines __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 .