其他分享
首页 > 其他分享> > 自定义rom

自定义rom

作者:互联网

class ORM:
    # 定义一个超类
    def save(self):
        print('获取类名', type(self).__name__)  # 推荐使用这个获取类名 User
        print('获取类名', self.__class__.__name__)  # User
        print('获取自定义属性', self.__dict__)  # {'name': 'tony', 'grade': 6, 'age': 12, 'score': 99, 'aaa': None}
        tablename = (self.__class__.__name__).lower()  # 类名转小写 user
        columns = "("
        values = "("
        for column in self.__dict__:  # 遍历字典(属性与值)信息,组装成columns(字段名) and values(值)
            print('column', column)
            columns += (column + ",")
            print(columns)
            """
            获取值的三种方式
            a = self.__getattribute__(column)
            b = getattr(self, column)
            self.__dict__[column]
            """
            if isinstance(self.__dict__[column], str):  # 判断字段是不是string类型
                values += "'" + self.__dict__[column] + "',"
            else:
                values += str(self.__dict__[column]) + ","

        columns = columns[:len(columns) - 1] + ")"
        print(columns)  # (name,grade,age,score,aaa)
        values = values[:len(values) - 1] + ")"
        print(values)  # ('tony',6,12,99,None)
        sql = "insert into " + tablename + " " + columns + " value " + values
        print(sql)  # 如果是入库操作,在这里替换成db cursor来执行sql即可。


class User(ORM):
    # 继承之上面定义的类,可以在实例化后直接调用save()保存方法
    def __init__(self, name, grade, age, score):
        self.name = name
        self.grade = grade
        self.age = age
        self.score = score
        self.aaa = None

    def abc(self):
        return 'cc'

    def __repr__(self):
        return 'User obj'


if __name__ == '__main__':
    u1 = User("tony", 6, 12, 99)
    u1.save()
    print(u1)  # User obj

标签:__,.__,rom,自定义,column,self,columns,name
来源: https://www.cnblogs.com/lxd670/p/16389023.html