2016-06-25 29 views
1

我正在使用带龙卷风的电机。我有以下类:DB在构造函数中的动态初始化

class N(): 
     def __init__(self,collectionName host='localhost', port=27017): 
     self.con=motor.MotorClient(host,port) 
     self.xDb=self.con.XDb 
     setattr(self,collectionName,self.xDb[collectionName]) 

这实际上是一个父类,我想扩展。子类将调用此类'init来设置collectionName。问题是我在这个类中还有一些其他的方法E.g.

@tornado.gen.coroutine 
    def dropDB(self): 
     yield self.xDb.drop_collection(self.COLLECTION??) 

,因为我动态设置集合中的初始化有什么办法,我可以决定自上述被打破。变量我设置为在基础方法中使用?

回答

2

设置另一个变量:

class N(): 
    def __init__(self, collectionName, host='localhost', port=27017): 
     # ... your existing code ... 
     self.collectionName = collectionName 

    @tornado.gen.coroutine 
    def dropDB(self): 
     yield self.xDb.drop_collection(self.collectionName) 

由于drop_collection需要一个名称或MotorCollection对象,还有你能保存这些数据self其他方式,但我的方式表现可能是最容易的。

http://motor.readthedocs.io/en/stable/api/motor_database.html#motor.motor_tornado.MotorDatabase.drop_collection