python的元类编程
廖雪峰的python教程有python元类编程示例,综合代码如下
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000#0
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('cls = %s' % cls) #print('name = %s' % name) #print('bases = %s' % bases) #print('attrs = %s' % 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] = vfor k in mappings.keys(): #attrs基本就是可以通过类的__dict__属性得到 attrs.pop(k) print(attrs) 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='test@orm.org', password='my-pwd') u.save()
完整的代码如上,运行时函数的调用如下。
1、u = User(xxxxx)进行User类的实例化
2、实例化User类的时候,调用User的__init__,未显式实现,则调用父类的__init__
3、在父类Model发现了父类有metaclass=ModelMetaclass
4、去执行ModelMetaclass的__new__
5、在__new__中,ModelMetaclass可以访问到类的(注意,是类的,而不是类实例的)name、bases、attr,从而进行操作实现类的动态修改
此处,attr可以发现User类的类变量(不是类实例变量)id、name、email、password,在外部,这些类变量可以由User.__dict__接触到
6、执行__new__的代码中,有一个从attr中pop某些key的过程,因为如果不pop掉这些key,会导致运行时类变量覆盖掉类实例的变量,得到不期望的结果
7、执行__new__的过程中,User类动态生成了__mapping__和__table__属性
8、完成__new__的执行后,再进行Model.__init__,然后是User.__init__,完成实例化
为什么在这种情况下要进行元类编程呢?有什么好处呢?