from pymongo import MongoClient
DBC = MongoClient("localhost").test.test
正如上面的代码段一样,我们只能使用.
代替get_database("test")
和get_collection("test")
来获取数据库实例或集合实例。尽管方便,但我想知道是什么让这个语法糖发生了?
答案 0 :(得分:2)
发生__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)