gj8 元类编程

8.1 property动态属性

from datetime import date, datetime

class 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 = value
if __name__ == "__main__":
    user = User("bobby", date(year=1987, month=1, day=1))
    user.age = 30
    print (user._age)
    print(user.age)
# ---
30
32

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 numbers

class 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):
        pass

class 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'))
# --- {} 30 30 # ---


class NonDataIntField: # 非数据属性描述符 def __get__(self, instance, owner): return self.value class 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} 30 30 # ------

''' 如果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")
        pass
a = 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 Company
if __name__ == "__main__":
    MyClass = create_class("user")
    my_obj = MyClass()
    print(type(my_obj))
---
<class '__main__.create_class.<locals>.User'> #type动态创建类 def say(self): # 定义的方法 return "i am user" # return self.name class 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()) # 调用基类方法

# ---
lewen i am user i am baseclass ---


#什么是元类, 元类是创建类的类 对象<-class(对象)<-type
from 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 numbers

class Field:
    pass

class 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 = value


class 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 = value


class 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))
        #pass


class 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()

image

 

image

posted @ 2019-02-12 18:28  前海渔文乐  阅读(781)  评论(0编辑  收藏  举报