class Field(object): def __init__(self, name, column_type): self.name = name self.column_type = column_type def __str__(self): return ‘<%s:%s‘ % (self.__class__.__name__, self.name) 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, ‘bigint‘) class ModelMetaclass(type): def __new__(cls, name, bases, attrs): #传入的是类的属性 if name==‘Model‘: return type.__new__(cls, name, bases, attrs) print(attrs) print(‘Found model: %s‘ % name) mappings = dict() for k, v in attrs.items(): if isinstance(v, Field): print(‘Found mapping: %s ==> %s‘ % (k, v)) 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, **kw): super(Model, self).__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"‘Model‘ object has no attribute ‘%s‘" % key) def __setattr__(self, key, value): 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: %s‘ % sql) print(‘ARGS: %s‘ % str(args)) class User(Model): # 定义类的属性到列的映射: id = IntegerField(‘id‘) name = StringField(‘username‘) email = StringField(‘email‘) password = StringField(‘password‘) u = User(id=12345, name=‘Michael‘, email=‘[email protected]‘, password=‘my-pwd‘,sdfjojf=‘sdfe‘) u.save()
当创建实例时,需要调用User类,首先会检查有没有__metaclass__属性,找到了,通过metalclass创建类(基于User类,传入的name为User,父类为Model,属性为User类的属性)。之后在实例化过程中,需要调用创建的新的User类中的方法,如果没有,需要到父类(metalclass创建新类会传承User类的父类)中查找,比如说之后会调用__init__方法,之后又调用save方法。
程序来源:
http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000
时间: 2024-10-11 17:25:44