• 【学习】面向对象高级编程(第六天)


    class Field:
        def __init__(self, name, col_type):
            self.name = name
            self.col_type = col_type
    
    class IntegerField(Field):
        def __init__(self, name):
            super(IntegerField, self).__init__(name, 'integer')
    
    class StringField(Field):
        def __init__(self, name):
            super(StringField, self).__init__(name, 'varchar(1024)')
    
    class ModelMetaclass(type):
        def __new__(cls, name, bases, attrs):
            if name == 'Model':
                return type.__new__(cls, name, bases, attrs)
            print('Model name: %s' % name)
            mappings = {}
            for k, v in attrs.items():
                if isinstance(v, Field):
                    print('Field name: %s' % k)
                    mappings[k] = v
            for k in mappings.keys():
                attrs.pop(k)
            attrs['__mappings__'] = mappings
            attrs['__table__'] = name
            return type.__new__(cls, name, bases, attrs)
    
    class Model(dict, metaclass = ModelMetaclass):
        def __init__(self, **kvs):
            super(Model, self).__init__(**kvs)
    
        def __getattr__(self, key):
            try:
                return self[key]
            except KeyError:
                raise AttributeError("'Model' object has no attribute '%s'." % key)
    
        def __setattr__(self, key, value):
            print('__setattr__')
            self[key] = value
    
        def save(self):
            fields = []
            params = []
            args = []
            for k, v in self.__mappings__.items():
                fields.append(v.name)
                params.append('?')
                args.append(getattr(self, k, None))
            sql = 'insert into %s(%s) values(%s)' % (self.__table__, ','.join(fields), ','.join(params))
            print('sql:', sql)
            print('args:', args)
    
    class User(Model):
        id = IntegerField('id')
        name = StringField('name')
    
    # u = User(id = 100, name = 'Tom')
    u = User()
    u.id = 100
    u.name = 'Tom'
    u.save()

    前面是一段代码,一看就萌啊?

    学了几天,开始解析代码

  • 相关阅读:
    【转】免费搭建独立博客,WordPress+独立域名+独立空间
    MongoDB索引
    面向对象
    浏览器为webapp
    转载Chrome浏览器IOS
    浅淡Webservice、WSDL三种服务访问的方式(附案例)
    Plupload
    转载Yale CAS + .net Client 实现 SSO(6)
    java 对Hbase的基本操作
    【精】iOS开发视频教程下载
  • 原文地址:https://www.cnblogs.com/yizhenfeng/p/6945612.html
Copyright © 2020-2023  润新知