0

让我们考虑一下我有一些模型类:

class UserModel(Model):
    title = StringType()

class ItemModel(Model):
    ...

这里的模型只是一个验证器(示意图)。但是我有一个数据库(MongoDB),我想向模型添加一些操作。

class CRUDOperations(object):
   def get(self):
       return "Get Method"

我想以某种方式将 CRUDOperations “插入”到模型中,并希望它可以像: 一样被访问UserModel.crud.get(),即不创建实例。我试图这样做但失败了,这有一个常见的做法吗?

from schematics.models import Model
from schematics.types import StringType


class CRUDOperations(object):
    def __init__(self, model_cls):
            # Upd. i need access to model_cls to get
            # some class attributes like collection name, database name etc.
        self.model_cls = model_cls


    @classmethod
    def get_crud(cls, model_cls):
        cls.model_cls = model_cls
        return cls

    @classmethod
    def get(cls, oid=None):
            # and if i'll use mongo here i'll need to access pymongo driver
            # like this: cls.model_cls._col_.find_one({"_id": oid})
        return 'test ok! {}'.format(cls.model_cls)


class CRUDModel(Model):
    __crud__ = None

    def __init__(self, *args, **kwargs):
        super(CRUDModel, self).__init__(*args, **kwargs)
        print "CRUDModel.__init__"
        self.__crud__ = CRUDOperations(self).get_crud()

    @classmethod
    def crud(cls):
        if cls.__crud__ is None:    
            cls.__crud__ = CRUDOperations.get_crud(cls)
        return cls.__crud__


class TestModel(CRUDModel):
    title = StringType()    


def main():
    print TestModel.crud
    print TestModel.crud.get()

if __name__ == '__main__':
    main()

是的,我知道有很多错误,但我尝试了很多方法,所以它只是显示我拥有什么以及我需要做什么的代码(调用像 TestModel.crud.create({...}) 这样的模型的 crud 操作)

4

2 回答 2

0

我会制作一个需要初始化实例CRUDOperations的常规对象(没有类方法) 。CRUDModel

然后你通过@property 传递给它在CRUDModel内部变量中初始化_crud_一个CRUDOperations实例self,然后从那时起返回它。

有了它,您将拥有.crud命名空间的这种功能分离,这就是您想要的我猜。


it's tricky since i want to have classmethods to have access w/o make instance.

如果您不想创建一个新实例,.crud.那么也许您可以重命名所有CRUDOperations方法以具有前缀并制作接收参数crud_的实例函数。self

然后通过继承它来将该CRUDOperations类用作mixin 。CRUDModel然后您的函数仍将使用crud_前缀进行分段,您不必创建多个实例。

于 2013-08-09T14:03:12.437 回答
0

您在. CRUDOperations_ _ 因此它们不能作为. self__init__CRUDModelCRUDModel

您应该执行以下操作:

class CRUDModel(Model):
    __crud__ = CRUDOperations(CRUDModel)

此外,使用双下划线命名变量也是不好的做法。双下划线用于语言保留字。使用单个下划线。

于 2013-08-09T13:56:29.353 回答