collection.py
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
"""returns a collection curser from mongodb"""
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
Run Code Online (Sandbox Code Playgroud)
main.py
import sys
import os
import collection
def main():
pass
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
Run Code Online (Sandbox Code Playgroud)
这些文件位于同一目录中.main.py然而,当我跑步时,我收到一个错误:
Begin Main
Traceback (most recent call last):
File "main.py", line 23, in <module>
agents = Collection('hkpr_restore','agents')
NameError: name 'Collection' is not defined
Run Code Online (Sandbox Code Playgroud)
根据我的阅读,如果文件在同一目录中,我需要做的就是使用import collection.
我错过了什么吗?
你只是导入collection,而不是Collection.
要么from collection import Collection实例化,要么在实例化时使用完全限定名称:agents = collection.Collection('hkpr_restore','agents').