gpt4 book ai didi

python - Pymongo数据库对象客户端拥有什么属性?

转载 作者:行者123 更新时间:2023-11-30 22:30:04 26 4
gpt4 key购买 nike

我正在浏览 PyMongo tutorial还有一件事我不明白。

我们被证明可以创建这样的数据库集合:

>>>client = MongoClient()   
>>>print(client)

MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)

>>>db = client.test_database
>>>print(db)

Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database')

>>>collection = db.test_collection #posts is the collection.
>>>print(collection)

Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database'), 'test_collection')

我最初的想法是:“他们是否确保包含客户端的 test_database 属性和数据库的 test_collection 属性,只是为了使其能够与教程配合使用?”但进一步的实验表明,我可以通过这种方式使用任何我喜欢的“属性名称”创建数据库和集合!例如:

>>>client = MongoClient()
>>>db = client.foo
>>>print(db)

Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'foo')

>>>collection = db.bar
>>>print(collection)

Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'foo'), 'bar')

这在 Python 中是如何工作的?我尝试通过阅读 GitHub 存储库中的 pymongo 文件来理解它,但对于新手来说很难理解。

最佳答案

MongoClient 重写了一个“神奇”方法,__getattr__。每当您访问 MongoClient 对象上的属性(实际上不是该对象的属性或特性)时,例如当您访问“test_database”时,Python 解释器都会调用:

client.__getattr__("test_database")

The implementation of MongoClient.__getattr__然后创建一个数据库对象并返回它。

数据库还覆盖 __getattr__ 以返回具有任意名称的集合。

这两个类还重写__getitem__,以便括号内的访问有效:

client["test_database"]

See the __getattr__ docs here .

关于python - Pymongo数据库对象客户端拥有什么属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46180992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com