python type、isinstance和metaclass的应用
python type、isinstance和metaclass的应用
在Python中可以用内置函数type查看对象的类型,isinstance查看某个对象是某个类实例,通过type可以实现动态类,以及通过metaclass实现动态类
type()与isinstance()判断对象类型
import types
class Hello():
def hello(self, name='World'):
print('hello %s' % name)
h = Hello()
type(h) == types.InstanceType //True
type(Hello)==types.ClassType //True
type(isinstance)==types.BuiltinFunctionType //True
isinstance(h, Hello) //True
lst = [1, 2, 3]
isinstance(lst, (int, str, list)) //True
type()可以得出对象的类型,类型定义在types module中。
isinstance(object, class-or-type-or-tuple) -> bool判断一个对象是某个类或子类的实例。
type()实现动态类
type()另一个功能是动态的创建一个类型
>>> def fn(self, name='world'):
... print('hello %s' % name)
...
>>> HH = type('Hello', (object,),dict(hello=fn))
>>> h = HH()
>>> h.hello()
hello world
type()的三个参数:
1)class的名称;
2)继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
3)class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
metaclass
#!/usr/bin/env python
# -*- coding: utf-8 -*-
' Simple ORM using metaclass '
__author__ = 'Michael Liao'
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('Found model: %s' % name)
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['__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__.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))
# testing code:
class User(Model):
id = IntegerField('uid')
name = StringField('username')
email = StringField('email')
password = StringField('password')
u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
u.save()
评论关闭