1

我已经开始编写一个简单的模块供 mongodb 使用。我是 python 新手,我写的代码有问题:

import pymongo


class mongoDB():

    conn = object

    def __init__(self):
        global conn
        self.conn = pymongo.Connection("localhost",27017)

    def CreateCollection(self,name =""):
        self.dbCollection  = conn.name
        return self.dbCollection

if __name__ == '__main__':
    database = mongoDB
    collection = database.CreateCollection("Hello")

首先,如果您能发现并纠正我,我认为我的代码可能没有什么问题。我也不断收到这个错误:

collection = database.CreateCollection("Hello")
TypeError: unbound method CreateCollection() must be called with mongoDB      

instance as first argument (got str instance instead)

我希望能够在类的构造函数中创建连接,然后有一个创建集合并返回它的方法,以及另一个插入删除和更新实体的方法

4

2 回答 2

18

所以,从语法上讲,你有很多问题。看起来您正在以不同的方式混合几个教程。所以,首先我将解释你的代码发生了什么,并解释为什么你会看到你所看到的:

import pymongo

class mongoDB():  # you don't need ()'s here - only if you are inheriting classes
                  # you could inherit from object here, which is a good practice
                  # by doing class mongoDb(object):, otherwise you can just take
                  # them out

    conn = object # here, you're defining a class member - global for all instances
                  # generally, you don't instantiate an object pointer like this,
                  # you would set it to None instead.  It won't fail doing this,
                  # but it's not "right"

    def __init__(self):
        # the __init__ method is the constructor method - this will 
        # allow you to initialize a particular instance of your class, represented
        # by the self argument.  This method is called when you call the class, i.e.
        # inst = mongoDb()

        # in this case, the conn variable is not a global.  Globals are defined
        # at the root module level - so in this example, only pymongo is a global
        # conn is a class member, and would be accessed by doing mongoDB.conn
        global conn

        # with that being said, you're initializing a local variable here called conn
        # that is not being stored anywhere - when this method finishes, this variable
        # will be cleaned up from memory, what you are thinking you're doing here
        # should be written as mongoDB.conn = pymongo.Connection("localhost", 27017)
        conn = pymongo.Connection("localhost",27017)

    def CreateCollection(name =""):
        # there is one of two things you are trying to do here - 1, access a class 
        # level member called conn, or 2, access an instance member called conn

        # depending on what you are going for, there are a couple of different ways 
        # to address it.

        # all methods for a class, by default, are instance methods - and all of them
        # need to take self as the first argument.  An instance method of a class
        # will always be called with the instance first.  Your error is caused because
        # you should declare the method as:

        # def CreateCollection(self, name = ""):

        # The alternative, is to define this method as a static method of the class -
        # which does not take an instance but applies to all instances of the class
        # to do that, you would add a @staticmethod decorator before the method.

        # either way, you're attempting to access the global variable "conn" here,
        # which again does not exist

        # the second problem with this, is that you are trying to take your variable
        # argument (name) and use it as a property.  What python is doing here, is
        # looking for a member variable called name from the conn object.  What you
        # are really trying to do is create a collection on the connection with the
        # inputed name

        # the pymongo class provides access to your collections via this method as a
        # convenience around the method, create_collection.  In the case where you
        # are using a variable to create the collection, you would call this by doing

        # conn.create_collection(name)

        # but again, that assumes conn is what you think it is, which it isn't
        dbCollection  = conn.name
        return dbCollection

if __name__ == '__main__':
    # here you are just creating a pointer to your class, not instantiating it
    # you are looking for:

    # database = mongoDB()
    database = mongoDB

    # this is your error, because of the afore mentioned lack of 'self' argument
    collection = database.CreateCollection("Hello")

我想说看看 Pep-8 (http://www.python.org/dev/peps/pep-0008/) 编码风格指南(非常有帮助)来了解如何让你的代码“流动”蟒蛇。

通过您的代码来解释发生了什么 - 这就是您最终想要做的事情:

import pymongo

class MongoDB: # Classes generally are camel-case, starting with uppercase
    def __init__(self, dbname):
        # the __init__ method is the class constructor, where you define
        # instance members.  We'll make conn an instance member rather
        # than a class level member
        self._conn = pymongo.Connection("localhost", 27017)
        self._db   = self._conn[dbname]

    # methods usually start with lowercase, and are either camel case (less desirable
    # by Python standards) or underscored (more desirable)
    # All instance methods require the 1st argument to be self (pointer to the
    # instance being affected)
    def createCollection(self, name=""):
        return self._db[name]

if __name__ == '__main__':
    # you want to initialize the class
    database   = MongoDB("Hello")
    collection = database.createCollection("MyTable")

鉴于此 - 编写此类包装器的目标是什么?同样可以写成:

import pymongo
conn       = pymongo.Connection('localhost', 27017)
database   = conn["Hello"]
collection = database["MyTable"]

如果您正在尝试创建一个更大的 API 围绕 pymongo 数据库,那么我建议您查看一些已经构建的 ORM 模块。有一些 - 不是 100% 确定哪些可用于 MongoDB,但我使用的(我有偏见,我写的)称为 ORB,可以在http://docs.projexsoftware.com/找到api/orb

于 2012-08-06T17:38:30.413 回答
1

这不是如何解决您的问题的具体答案,而是如何逐步完成您想要做的事情并在出现更简单的问题时解决问题的答案:

1) 首先忘记课程,而是

2) 使用 Python 命令行或 IDLE 之类的 Python 程序,

3) 通过编写调用打开 MongoDB 数据库来完成您的任务或任务来建立您的目标。换句话说,在担心类之前,先编写最简单的代码来实现你的目标。

4)一旦你完成了,并且感觉很好继续前进,然后使用文档编写一个测试类。我的链接是您能找到的众多链接之一。

5)我认为您的问题的一部分但不是全部是您的课程设置不正确。我的班级 - 未完全显示 - 如下:

class GlobalData:
    def set_xfer_date(self, value):
        self.xfer_date = value
        self.date_str = str(value)
        self.xfer_date_base = self.date_str[0:10] + " " + "00:00:00"

        # Now build tomorrow.
        self.xfer_date_tomorrow = datetime.today() + timedelta(1)
        self.date_str_tomorrow = str(self.xfer_date_tomorrow) 
        self.xfer_date_tomorrow = \
          self.date_str_tomorrow[0:10] + " " + "00:00:00" 

        self.section_totals = {}
        self.billable_reads = {}

    def set_xfer_fnam_out(self, value):
        self.xfer_fnam_out = value

    def set_xfer_dir_in(self, value):
        self.xfer_dir_in = value
    .
    .
    .

    def get_billable_reads(self):
        return self.billable_reads

我看到的问题之一是您没有使用self. Good lucky 来引用数据。

于 2012-08-06T17:42:56.480 回答