> 元类
元类就是创建类的类,主要作用就是拦截类的创建,然后修改一些特性,最后返回该类。
首先认识一下python地内建元类——type。主要用于动态地创建一个类,当然还有常用的查看对象类型功能。
语法如下:
type(类名, 父类的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))
class testClass():
pass
class testChildClass(testClass):
name = Jack
等价:
type("testChildClass", (testClass), {'name': 'Jack'})
使元类改变类示例:
class myMetaClass(type):
def __new__(cls, name, bases, attrs):
print(cls, name, bases, attrs)
attrs['__mappings__'] = {'a': 'A', 'b':'B'}
return super(myMetaClass,cls).__new__(cls, name, bases, attrs)
class myClass(metaclass=myMetaClass):
#__metaclass__ = ModelMetaclass ##python2.x
def __init__(self):
print(self.__mappings__)
a = myClass()
结果:
<class '__main__.myMetaClass'> myClass () {'__module__': '__main__', '__qualname__': 'myClass',
'__init__': <function myClass.__init__ at 0x00000208C15342F0>}
{'a': 'A', 'b': 'B'}
> ORM
对象关系映射(英语:(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。
使用元类创建一个类似Django中的ORM示例:
#coding:utf-8
#一、首先来定义Field类,它负责保存数据库表的字段名和字段类型:
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')
#二、定义元类,控制Model对象的创建
class ModelMetaclass(type):
'''定义元类'''
def __new__(cls, name, bases, attrs):
if name=='Model':
return super(ModelMetaclass,cls).__new__(cls, name, bases, attrs)
mappings = dict()
for k, v in attrs.items():
# 保存类属性和列的映射关系到mappings字典
if isinstance(v, Field):
print(k, v)
mappings[k] = v
for k in mappings.keys():
#将类属性移除,使定义的类字段不污染User类属性,只在实例中可以访问这些key
attrs.pop(k)
attrs['__table__'] = name.lower() # 假设表名和为类名的小写,创建类时添加一个__table__类属性
attrs['__mappings__'] = mappings # 保存属性和列的映射关系,创建类时添加一个__mappings__类属性
return super(ModelMetaclass,cls).__new__(cls, name, bases, attrs)
#三、编写Model基类
class Model(dict, metaclass=ModelMetaclass):
# __metaclass__ = ModelMetaclass python2.x
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 = []
args = []
for k, v in self.__mappings__.items():
fields.append(v.name)
args.append(getattr(self, k, None))
sql = 'insert into %s (%s) values %s' % (self.__table__, ', '.join(fields), str(tuple(args)))
print('SQL: %s' % sql)
# 定义类的属性到列的映射:
class User(Model):
id = IntegerField('id')
name = StringField('username')
email = StringField('email')
password = StringField('password')
# 创建一个实例:
u = User(id=123, name='Jack', email='123@qq.com', password='****')
# 保存到数据库:
u.save()
结果:
id <IntegerField:id>
name <StringField:username>
email <StringField:email>
password <StringField:password>
SQL: insert into user (id, username, email, password) values (123, 'Jack', '123@qq.com', '****')