时间:2021-07-01 10:21:17 帮助过:19人阅读
元类
import pymysql class Field(object): def __init__(self,name,column_type): self.name = name self.column_type = column_type def __str__(self): return "<%s:%s>"%(self.name,self.column_type) class StringField(Field): def __init__(self,name): super(StringField,self).__init__(name,"varchar(100)") class IntegerField(Field): def __init__(self,name): super(IntegerField,self).__init__(name,"int") class ModelMetaClass(type): def __new__(cls, name,bases,attrs): ‘‘‘ :param name: 类的名称 :param bases: 类的继承 :param attrs: 类的属性 :return: ‘‘‘ if name == "Model": return type.__new__(cls,name,bases,attrs) mapping = dict() #空字典 for k,v in attrs.items(): #遍历属性 if isinstance(v,Field): #判断属性是否Field的实例 mapping[k] = v #添加到mapping当中 for k in mapping.keys(): #返回所有键 attrs.pop(k) #从属性当中删除 attrs["__mapping__"] = mapping #设定__mapping__属性来保存字段 attrs["__table__"] = name return type.__new__(cls,name,bases,attrs) class Model(dict,metaclass = ModelMetaClass): def __init__(self,**kwargs): self.db = pymysql.connect( host = "localhost", user = "root", password = "123", database = "test" ) self.cursor = self.db.cursor() super(Model,self).__init__(**kwargs) def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value def save(self): fields = [] #空列表用来存储字段 args = [] #空列表用来存储字段的值 for k,v in self.__mapping__.items(): fields.append(v.name) args.append(getattr(self,k,None)) sql = "insert into %s(%s) values (%s)"%( self.__table__, ",".join(fields), ",".join([repr(str(i)) for i in args] )) #sql拼接 self.cursor.execute(sql) print(sql) def __del__(self): ‘‘‘ 回收内存 ‘‘‘ self.db.commit() self.cursor.close() self.db.close() class Student(Model): name = StringField("name") room_id = IntegerField("room_id") u = Student(name = "老边",room_id = 18) u.save()
元类,sqlalchemy查询
标签:self 保存 init style save let tac type one