首页 > 代码库 > 关于廖雪峰提到的元类的应用实例的解释
关于廖雪峰提到的元类的应用实例的解释
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=‘test@orm.org‘, 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
关于廖雪峰提到的元类的应用实例的解释
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。