元类,以及使用元类去实现数据库的操作

元类

type(类名,(父类名.....),{"键","值}


第一种方式
def xxxx(类名,父类名...,属性):
    return type(类名,父类名...,属性)

第二种方式
class Xxx(type):这个必须继承type
    def __new__(cls,类名,父类名....,属性):
        return type.__new__(cls,类名,父类名...,属性)

#用法
class A(object,metaclass=上面的引用)
    pass

元类实现数据库的操作

from pymysql import connect

class my_meta_class(type):

def __new__(cls,class_name,super_names,atrrs):
    print(atrrs)
    #自动生成一个字典
    #如果是元组是就是我写的属性
    fields_dict = dict()
    for key,value in atrrs.items():
        #判断如果是元组就是我们的数据
        if isinstance(value,tuple):
            fields_dict[key] = value[0]

    print(fields_dict)

    #把新生成的字典加入
    atrrs["field_dict"] = fields_dict
    # return type(class_name,super_names,atrrs)

    #表名换成类名
    atrrs['table_name'] = class_name
    return type.__new__(cls,class_name,super_names,atrrs)

class Table(object,metaclass=my_meta_class):

#创建一个表
def create(self):
    #1.连接数据库
    #连接上数据库
    conn = connect(host='localhost', port=3306, user="root", password="mysql", database="jing_dong", charset='utf8')
    #得到游标对象
    cs1 = conn.cursor()
    #sql语句
    # create_sql = """CREATE TABLE IF NOT EXISTS user(uid int unsigned,name varchar(30),email varchar(30),password varchar(30)); """
    #把字段放到字典中
    # field_dict = {"uid":"int unsigned","name":"varchar(30)","email":"varchar(30)","password":"varchar(30)","classname":"varchar(30)"}

    #把字段存到列表中
    field_list = list()

    #动态去拼接字段
    for key,value in self.field_dict.items():
        field_list.append("%s %s"%(key,value))


    #拼接列表
    create_sql = """CREATE TABLE IF NOT EXISTS %s(%s); """%(self.table_name,",".join(field_list),)
    print(create_sql)

    # 2执行Sql语句
    cs1.execute(create_sql)

    #执行语句
    conn.commit()

    #关闭
    cs1.close()
    conn.close()
#############上面是框架,下面具体实现

class Student(Table):
name = (“varchar(30)”,)
age = (“int”,)

class PP(Table):
name = (“varchar(30)”,)
age = (“int”,)

def main():
student = Student()
student.create()

pp = PP()
pp.create()

if name == ‘main‘:
main()

猜你喜欢

转载自blog.csdn.net/qq_41868948/article/details/80069536
今日推荐