博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
gj8 元类编程
阅读量:6435 次
发布时间:2019-06-23

本文共 8307 字,大约阅读时间需要 27 分钟。

8.1 property动态属性

from datetime import date, datetimeclass User:    def __init__(self, name, birthday):        self.name = name        self.birthday = birthday        self._age = 0  #     #def get_age(self):        #return datetime.now().year - self.birthday.year    @property    # 将函数变成属性的方式访问,可以通过 user.age 访问     def age(self):        return datetime.now().year - self.birthday.year    @age.setter  # 设置属性  user.age = 24    def age(self, value):        self._age = valueif __name__ == "__main__":    user = User("bobby", date(year=1987, month=1, day=1))    user.age = 30    print (user._age)    print(user.age)# ---3032

8.2 __getattr__、__getattribute__魔法函数

# __getattr__, __getattribute__# __getattr__ 就是在查找不到属性的时候调用class User:    def __init__(self, info={}):        self.info = info    def __getattr__(self, item):  # 属性不存在的时候,进入        return self.info[item]        # return "not find "    # def __getattribute__(self, item):   # 无条件的进入,所有属性的访问入口    #     return "lewen"if __name__ == "__main__":    user = User(info={"company_name": "imooc", "name": "lewen"})    print(user.name)
---
lewen

8.3 属性描述符和属性查找过程

import numbersclass IntField:    # 数据属性描述符,任意实现下面一个就是    def __get__(self, instance, owner):  #        return self.value    def __set__(self, instance, value):        if not isinstance(value, numbers.Integral):  # 参数类型检查            raise ValueError("int value need")        if value < 0:            raise ValueError("positive value need")        self.value = value    def __delete__(self, instance):        passclass User:    age = IntField()if __name__ == "__main__":    user = User()    user.age = 30#     user.__dict__["age"] = "abc"   #  print(user.age) 会报错,找不到value    print(user.__dict__) # {} 并没有进入对象实例    print(user.age)    print (getattr(user, 'age')) # ---{}3030# --- class NonDataIntField:    # 非数据属性描述符    def __get__(self, instance, owner):        return self.valueclass User:    age = NonDataIntField()if __name__ == "__main__":    user = User()    user.age = 30    print(user.__dict__) # {'age': 30}    print(user.age)    print (getattr(user, 'age')) # ==={'age': 30}3030# ------ '''如果user是某个类的实例,那么user.age(以及等价的getattr(user,’age’))首先调用__getattribute__。如果类定义了__getattr__方法,那么在__getattribute__抛出 AttributeError 的时候就会调用到__getattr__,而对于描述符(__get__)的调用,则是发生在__getattribute__内部的。user = User(), 那么user.age 顺序如下:(1)如果“age”是出现在User或其基类的__dict__中, 且age是data descriptor, 那么调用其__get__方法, 否则(2)如果“age”出现在user的__dict__中, 那么直接返回 obj.__dict__[‘age’], 否则(3)如果“age”出现在User或其基类的__dict__中,如果age是non-data descriptor,那么调用其__get__方法, 否则返回 __dict__[‘age’](4)如果User有__getattr__方法,调用__getattr__方法,否则(5)抛出AttributeError'''

8.4 __new__和__init__的区别

class User:    def __new__(cls, *args, **kwargs):        print (" in new ")        return super().__new__(cls)    def __init__(self, name):        print (" in init")        passa = int()#new 是用来控制对象的生成过程, 在对象生成之前#init是用来完善对象的#如果new方法不返回对象, 则不会调用init函数if __name__ == "__main__":    user = User(name="bobby")--- in new in init

8.5 自定义元类

#类也是对象,type创建类的类def create_class(name):    if name == "user":        class User:            def __str__(self):                return "user"        return User    elif name == "company":        class Company:            def __str__(self):                return "company"        return Companyif __name__ == "__main__":    MyClass = create_class("user")    my_obj = MyClass()    print(type(my_obj))--- 
.User'>#type动态创建类def say(self): # 定义的方法 return "i am user" # return self.nameclass BaseClass(): # 基类 def answer(self): return "i am baseclass"User = type("User", (BaseClass,), {"name":"lewen","say":say})# 类名 模板 属性my_obj = User()print(my_obj.name)print(my_obj.say()) # 调用方法print(my_obj.answer()) # 调用基类方法
# ---leweni am useri am baseclass---
 
#什么是元类, 元类是创建类的类 对象<-class(对象)<-typefrom collections.abc import *class MetaClass(type):                      # 控制实例化的过程    def __new__(cls, *args, **kwargs):      # 作初始检查        return super().__new__(cls, *args, **kwargs)class User(metaclass=MetaClass):    def __init__(self, name):        self.name = name    def __str__(self):        return "user:%s"%(self.name)# python中类的实例化过程,会首先寻找metaclass,通过metaclass去创建user类.# 没有继承的metaclass找到 则最后由 # type去创建类对象,实例my_obj = User("lewen")print(my_obj)
---user:lewen

8.6 元类实现简单的orm

import numbersclass Field:    passclass IntField(Field):    # 数据描述符    def __init__(self, db_column, min_value=None, max_value=None):        self._value = None        self.min_value = min_value        self.max_value = max_value        self.db_column = db_column        if min_value is not None:            if not isinstance(min_value, numbers.Integral):                raise ValueError("min_value must be int")            elif min_value < 0:                raise ValueError("min_value must be positive int")        if max_value is not None:            if not isinstance(max_value, numbers.Integral):                raise ValueError("max_value must be int")            elif max_value < 0:                raise ValueError("max_value must be positive int")        if min_value is not None and max_value is not None:            if min_value > max_value:                raise ValueError("min_value must be smaller than max_value")    def __get__(self, instance, owner):        return self._value    def __set__(self, instance, value):        if not isinstance(value, numbers.Integral):            raise ValueError("int value need")        if value < self.min_value or value > self.max_value:            raise ValueError("value must between min_value and max_value")        self._value = valueclass CharField(Field):    def __init__(self, db_column, max_length=None):        self._value = None        self.db_column = db_column        if max_length is None:            raise ValueError("you must spcify max_lenth for charfiled")        self.max_length = max_length    def __get__(self, instance, owner):        return self._value    def __set__(self, instance, value):        if not isinstance(value, str):            raise ValueError("string value need")        if len(value) > self.max_length:            raise ValueError("value len excess len of max_length")        self._value = valueclass ModelMetaClass(type):    def __new__(cls, name, bases, attrs, **kwargs):        if name == "BaseModel":  # 反回 BaseModel 类            return super().__new__(cls, name, bases, attrs, **kwargs)        # 子类的数据封装        fields = {}        for key, value in attrs.items():            if isinstance(value, Field):  # 封装属性字段值                fields[key] = value        attrs_meta = attrs.get("Meta", None)  # 获取User类中的 Meta 类对象        _meta = {}        db_table = name.lower()  # 默认表名        if attrs_meta is not None:  #            table = getattr(attrs_meta, "db_table", None)            if table is not None:                db_table = table        _meta["db_table"] = db_table  # 设置表名        attrs["_meta"] = _meta        attrs["fields"] = fields        del attrs["Meta"]        return super().__new__(cls, name, bases, attrs, **kwargs)# 先__new__将创建类的数据进行封装并返回类对象 ,再__init__初始化class BaseModel(metaclass=ModelMetaClass):    # 处理子类实例化时初始值    def __init__(self, *args, **kwargs):        for key, value in kwargs.items():            setattr(self, key, value)        return super().__init__()        #?        # 反回__init__方法,子类中不需要定义    def save(self):        fields = []        values = []        for key, value in self.fields.items():            db_column = value.db_column            if db_column is None:                db_column = key.lower()            fields.append(db_column)            value = getattr(self, key)            values.append(str(value))        sql = "insert {db_table}({fields}) value({values})".format(db_table=self._meta["db_table"],                                                                   fields=",".join(fields), values=",".join(values))        #passclass User(BaseModel):  # 创建类触发__new__: 类名User, bases 为BaseModel,下面的是属性 attrs    name = CharField(db_column="name", max_length=10)    age = IntField(db_column="age", min_value=1, max_value=100)    class Meta:        db_table = "user"if __name__ == "__main__":    user = User(name="lewen", age=28)  # 实例化,触发__init__    # user.name = "bobby"    # user.age = 28    user.save()

 

转载于:https://www.cnblogs.com/wenyule/p/10366646.html

你可能感兴趣的文章
七牛云存储Python SDK使用教程 - 上传策略详解
查看>>
友盟开放日: 通过 App 内社区提高留存率的 6 个技巧
查看>>
Git + Maven + Jenkins 实现自动化部署
查看>>
js动画之无缝滚动
查看>>
flag -- 诡异的memcache标记
查看>>
[20180428]DNS与ORA-12154错误.txt
查看>>
被遗忘的图灵:计算机、神经网络、人工智能……他是这一切之父
查看>>
安卓Hawk数据库
查看>>
Linux系统下不同机器之间拷贝文件的方法
查看>>
IBM科学家实现存储器重大突破
查看>>
TIP 2018论文概述:基于深度学习的HEVC复杂度优化
查看>>
淘宝心选在大润发开店了,背后意味着什么?
查看>>
你知道我们平时在CSS中写的%都是相对于谁吗?
查看>>
六种排序算法的JavaScript实现以及总结
查看>>
VueJS && ReactJS 如何?听听别人怎么说。
查看>>
另一个角度的架构师
查看>>
设计模式(Design Patterns)详解
查看>>
【开发者的精进】 数据驱动下的程序设计
查看>>
Android音乐、视频类APP常用控件:DraggablePanel(2)
查看>>
图文直播:Pokémon Go真爱粉与“脑残粉”之间的爱恨情仇
查看>>