2016-07-19 4 views
2
from pymongo import MongoClient 
DBC = MongoClient("localhost").test.test 

上記のスニペットと同様に、get_database("test")get_collection("test")の代わりに.だけを使用して、データベースインスタンスまたはコレクションインスタンスを取得できます。利便性にもかかわらず、何がこれを作るのだろうか構文的な砂糖は起こるか?pymongoなぜドットを使ってコレクションインスタンスを取得できますか?

答えて

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) 

same goes for the Database class

関連する問題