Python 将方法容器添加到另一个类 让我考虑一下我有一些模型类: class UserModel(Model): title = StringType() class ItemModel(Model): ...
这里的模型只是一个验证器(示意图)。但我有一个数据库(MongoDB),我想向模型中添加一些操作Python 将方法容器添加到另一个类 让我考虑一下我有一些模型类: class UserModel(Model): title = StringType() class ItemModel(Model): ...,python,api,rest,instantiation,Python,Api,Rest,Instantiation,这里的模型只是一个验证器(示意图)。但我有一个数据库(MongoDB),我想向模型中添加一些操作 class CRUDOperations(object): def get(self): return "Get Method" 我想以某种方式将CrudoOperations“插入”到模型中,并希望像这样访问它:UserModel.crud.get(),即不创建实例。我试着这么做,但失败了,有没有一个共同的做法呢 from schematics.models import M
class CRUDOperations(object):
def get(self):
return "Get Method"
我想以某种方式将CrudoOperations“插入”到模型中,并希望像这样访问它: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操作)您的
CRUDOperations
在CRUDModel
的方法中用self
实例化。因此它们不能作为类操作在CRUDModel
上访问
你应该这样做:
class CRUDModel(Model):
__crud__ = CRUDOperations(CRUDModel)
此外,使用双下划线命名变量也是一种不好的做法。双下划线表示语言保留字。使用单下划线。我将使CRUDOperations
成为一个常规对象(没有类方法),它需要一个CRUDModel
实例来初始化
然后在CRUDModel
上创建一个@property
crud,通过向其传递self
来初始化内部变量\u crud
一个CRUDOperations
实例,然后返回它
这样,您就可以将函数分离到.crud
名称空间,我想这就是您想要的
如果您不想创建一个新实例来拥有.crud.
,那么您可以重命名所有CRUDOperations
方法,使其具有前缀crud
,并使实例函数接收一个self
参数
然后使用CRUDOperations
类作为mixin,方法是继承CRUDModel
类。然后,您的函数仍将使用crud\uu
前缀进行分段,并且您不必创建多个实例。我几乎尝试了包括@property在内的所有方法,这很棘手,因为我想让classmethods在不生成实例的情况下进行访问。@isting检查我的编辑,可能会有所帮助。我不知道还有其他任何实际的方法可以做到这一点。CRUDModel的子类定义了一些属性,如集合、mongo_连接、数据库等。我需要从CrudoOperations访问最终的模型类。
it's tricky since i want to have classmethods to have access w/o make instance.