一个类作为metaclass的时候,我们需要重写它的__new__方法,这个方法的参数包括要创建class object的 metaclass,类名,父类集合,类成员
class MyMetaclass(type):
def __new__(metaclz,name,bases,attrs):
print("create new class ",metaclz,name)
return type.__new__(metaclz, name, bases, attrs)
这样在调用__new__的时候,就给了我们一些发挥的空间了,一般我们可以修改bases、attrs中的成员,或则根据这自己定义的一些规则做一些特别的事情。
比如,可以利用这个来写测试框架、代码规则检测,装饰类的方法,写ORM框架等等。
ORM框架大致demo:
# -*- coding:utf-8 -*- 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):
#一般的ORM框架这里应该通过bases来处理
if name=='Model':
return type.__new__(cls, name, bases, attrs)
mappings = dict() #取出 数据库中的字段
for k, v in attrs.iteritems():
if isinstance(v, Field):
print('Found mapping: %s==>%s' % (k, v))
mappings[k] = v
#删除相关的类成员
for k in mappings.iterkeys():
attrs.pop(k)
attrs['__table__'] = name # 假设表名和类名一致
attrs['__mappings__'] = mappings # 保存属性和列的映射关系
return type.__new__(cls, name, bases, attrs) class Model(dict):
__metaclass__ = ModelMetaclass def __init__(self, **kw):
print("kw:",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__.iteritems():
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',zz='4555')
u.save()