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
主.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
这些文件在同一目录中。但是,当我运行 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
据我所知,如果文件在同一个目录中,我需要做的就是使用import collection。
我错过了什么吗?
请您参考如下方法:
您只导入了 collection , 不是 Collection .
或者from collection import Collection , 或在实例化时使用全限定名:agents = collection.Collection('hkpr_restore','agents') .
