簡體   English   中英

為什么我的Python腳本無法識別導入模塊中的類?

[英]Why doesn't my Python script recognize a class from an imported module?

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

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

這些文件在同一目錄中。 但是,當我運行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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM