python中类中的类,如何共享信息

时间:2016-07-12 09:14:20

标签: python database peewee

我正在尝试使用python中的peewee为数据库创建一个类。由于peewee在模型中使用了一个名为meta的类,因此导致嵌套类。我的问题是,如何在Meta类中定义数据库(= db)?还有更好的方法吗?

import peewee as pe

    class DataBase():
        class SensorType(pe.Model):
            name = pe.CharField(max_length=255, unique=True)

            class Meta:
                database = db

    def ___init___(self,filename='sensors.db'):
        db = pe.SqliteDatabase(filename)
        db.connect()
        db.create_tables([self.SensorType],safe=True)

    def add_sensor(self,typeName):
        type, created = self.SensorType.get_or_create(name=typeName)
        return type, created

    def get_sensors(self):
        return self.SensorType.select().order_by(self.SensorType.name)


if __name__ == '__main__':

    myDb = DataBase()
    myDb.add_sensor('Test')

    for type in myDb.get_sensors():     
        print(type.name) 

我发现在我的主类的__init__函数中定义类是有效的。但它可能不是首选方法。

import peewee as pe

class DataBase():
    def __init__(self,filename='sensors.db'):        
       db = pe.SqliteDatabase(filename)
       db.connect()

        class SensorType(pe.Model):
           typename = pe.CharField(max_length=255, unique=True)
           class Meta:
              database = db             

       self.SensorType = SensorType          
       db.create_tables([self.SensorType],safe=True)


    def add_sensor_type(self,typeName):
       type, created = self.SensorType.get_or_create(typename=typeName)
       return type, created

    def get_sensor_types(self):
       return self.SensorType.select()

if __name__ == '__main__':

    myDb = DataBase()
    myDb.add_sensor_type('Test')

    for type in myDb.get_sensor_types():     
        print(type.id, type.typename)

2 个答案:

答案 0 :(得分:2)

尝试继承,而不是嵌套类。 This post有一些关于如何在Python中使用继承和元类的相当不错的信息。

查看peewee的快速入门示例,这样的事情对你有用吗?

import peewee

class BaseModel(peewee.Model):            
    def __init__(self, db):
        super(BaseModel, self).__init__()
        Meta.database = db

    class Meta:
        database = None

class SensorType(BaseModel):
    def __init__(self, db):
        super(SensorType, self).__init__(db)

    name = peewee.CharField(max_length=255, unique=True)

class DataBase():
    def __init__(self, filename='sensors.db'):
        self.db = peewee.SqliteDatabase(filename)
        self.sensor_type = SensorType(self.db)
        self.db.connect()
        self.db.create_tables([self.sensor_type], safe=True)

    def add_sensor(self, typeName):
        type, created = self.sensor_type.get_or_create(name=typeName)
        return type, created

    def get_sensors(self):
        return self.sensor_type.select().order_by(self.sensor_type.name)

if __name__ == '__main__':
    db = DataBase()

    db.add_sensor('Test')
    [print(type.name) for type in db.get_sensors()]

使用模型的__init__方法查看是否可以在初始化时传递数据库实例。

我会远离在方法中定义一个类。

我希望这有帮助!

答案 1 :(得分:0)

我最终使用了peewee文档中的this approach。它有效,我避免使用嵌套类:

import peewee as pe
database = pe.SqliteDatabase(None)

class BaseModel(pe.Model):
    class Meta:
        database = database

class SensorType(BaseModel):
    name = pe.CharField(max_length=255, unique=True)

class DataBase():
    def __init__(self, filename='sensors.db'):
        database.init(filename)
        self.sensor_type = SensorType()
        database.connect()
        database.create_tables([self.sensor_type], safe=True)        

if __name__ == '__main__':
    db = DataBase('test.db')