python 的元类

一 引入

在 python 中,一切皆为对象,类其实也是对象,为什么这么说??类时通过调用元类产生的

二 什么是元类

元类就是用来实例化产生类的类,它的作用就是用来产生自定的类

关系:元类---->实例化------>类------>实例化------>对象(obj)

class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self):
        print('%s:%s'%(self.name, self.age))

# print(People.__dict__)
#如何得到对象
# obj = 调用类()
obj = People('egon', 18)
print(type(obj)) #<class '__main__.People'>
#如果说类也是对象
# People = 调用类()

查看内置的元类:

1、type 是内置的元类

2、我们用 class 关键字定义的所有类以及内置的类都是由元类 type 实例化产生的

print(type(People)) #<class 'type'>
print(type(int)) #<class 'type'>
print(type(str)) #<class 'type'>

三 class 关键字创造类的步骤

类有三大特征:

1、类名

class_name = "People"

2、类的基类

class_bases = (object,)

3、执行类体代码拿到类的名称空间

class_dic = {} #定义一个局部名称空间
class_body = """

def __init__(self, name, age):
    self.name = name
    self.age = age

def say(self):
    print('%s:%s'%(self.name, self.age))
"""

exec(class_body, {}, class_dic)
print(class_dic) #{'__init__': <function __init__ at 0x108382e18>, 'say': <function say at 0x108575378>}

补充:exec 的用法

#exec:三个参数

#参数一:包含一系列python代码的字符串

#参数二:全局作用域(字典形式),如果不指定,默认为globals()

#参数三:局部作用域(字典形式),如果不指定,默认为locals()

#可以把exec命令的执行当成是一个函数的执行,会将执行期间产生的名字存放于局部名称空间中

g={
    'x':1,
    'y':2
}
l={}

exec('''
global x,z
x=100
z=200

m=300
''',g,l)

print(g) #{'x': 100, 'y': 2,'z':200,......} 全局名称空间
print(l) #{'m': 300} 局部名称空间

4、调用元类

People = type(class_name, class_bases, class_dic)
print(People) #<class '__main__.People'>  

四 如何自定义元类来控制类的产生

1、自定义元类

class Mymeta(type): #只有继承了 type 类的类才是元类
    # def __init__(cls,*args, **kwargs):
    #     print(args) #args = (class_name, class_bases, class_dic)
    def __init__(self, class_name, class_bases, class_dic):
        super().__init__(class_name, class_bases, class_dic)
        print(self)  #<class '__main__.People'>
        print(class_name)  #People
        print(class_bases) #(<class 'object'>,)
        print(class_dic) #{'__init__': <function __init__ at 0x10e3ade18>, 'say': <function say at 0x10e5a0378>}
        if not class_name.istitle():
            raise NameError('类名的首字母必须大写啊')

        #当前所在的类,调用类时所传入的参数
    def __new__(cls, *args, **kwargs): #调用类产生新的空对象
        #造 Mymeta的对象
        print('__new__ run....')
        print(cls) #<class '__main__.Mymeta'>
        print(args) #('People', (<class 'object'>,), {...})
        print(kwargs) #{}

        # return super().__new__(cls, *args, **kwargs)
        return type.__new__(cls, *args, **kwargs) #<class '__main__.People'>

People = Mymeta(class_name,class_bases,class_dic)

# 结果展示
'''
先自动调用__new__方法,产生空对象
__new__ run....
<class '__main__.Mymeta'>
('People', (<class 'object'>,), {'__init__': <function __init__ at 0x10e3ade18>, 'say': <function say at 0x10e5a0378>})
{}

#然后再自动调用__init__方法,初始化对象
<class '__main__.People'>
People
(<class 'object'>,)
{'__init__': <function __init__ at 0x10e3ade18>, 'say': <function say at 0x10e5a0378>}
'''

调用 Mymeta 发生三件事,调用Myneta就是==> type.__ call __ ()
1、先造一个空对象==》People,调用Mymeta 类内的__ new __ 方法
2、调用 Mymeta这个类内的__ init __方法,完成初始化对象的操作
3、返回初始好的对象

2、定义类的过程详解

自定义元类可以控制类的产生过程,类的产生过程其实就是元类的调用过程

People = Mymeta() ---> type.__ call __ ==>干了3件事
1、type.__ call __ 函数内会先调用 Mymeta内的 __ new__
2、type.__ call __ 函数内会再调用Mymetan内的 __ init__
3、type.__ call__函数内会返回一个初始化好的对象

# class People(metaclass=Mymeta): #===》People = Mymeta('类名', (object,), 类的名称空间)
class People(metaclass=Mymeta): #===》People = Mymeta('People', (), {...})
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self):
        print('%s:%s' % (self.name, self.age))


# 结果展示
'''
__new__ run....
<class '__main__.Mymeta'>
('People', (), {'__module__': '__main__', '__qualname__': 'People', '__init__': <function People.__init__ at 0x101b71620>, 'say': <function People.say at 0x101b716a8>})
{}
<class '__main__.People'>
People
()
{'__module__': '__main__', '__qualname__': 'People', '__init__': <function People.__init__ at 0x101b71620>, 'say': <function People.say at 0x101b716a8>}
'''

强调:

只要是调用类,那么会依次调用:
1、类内的__ new __
2、类内的__ init __

案例:

class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
    def __init__(self,class_name,class_bases,class_dic):
        # print(self) #<class '__main__.StanfordTeacher'>
        # print(class_bases) #(<class 'object'>,)
        # print(class_dic) #{'__module__': '__main__', '__qualname__': 'StanfordTeacher', 'school': 'Stanford', '__init__': <function StanfordTeacher.__init__ at 0x102b95ae8>, 'say': <function StanfordTeacher.say at 0x10621c6a8>}
        super(Mymeta, self).__init__(class_name, class_bases, class_dic)  # 重用父类的功能

        if class_name.islower():
            raise TypeError('类名%s请修改为驼峰体' %class_name)

        if '__doc__' not in class_dic or len(class_dic['__doc__'].strip(' \n')) == 0:
            raise TypeError('类中必须有文档注释,并且文档注释不能为空')

# StanfordTeacher=Mymeta('StanfordTeacher',(object),{...})
class StanfordTeacher(object,metaclass=Mymeta): 
    """
    类StanfordTeacher的文档注释
    """
    school='Stanford'

    def __init__(self,name,age):
        self.name=name
        self.age=age

    def say(self):
        print('%s says welcome to the Stanford to learn Python' %self.name)

五 __ call __

在该类内部添加 __ call __方法,可以实现对象( )的调用

对象() --->类的__ call __
类() ----->自定义元类内的__ call __
自定义元类() ---->内置元类(type)的__ call __

class Foo:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __call__(self, *args, **kwargs):
        print('====>',args, kwargs)
        return "__call__ 触发了"

obj = Foo(111, 222)
# print(obj.__str__()) # <__main__.Foo object at 0x10223f898> 默认返回的是对象的内存地址
print(obj) # 等同于 obj.__str___

#应用: 对象加空号调用,需要在该对象的类中添加一个方法__call__
res = obj(1,2,3, a=4, b=5, c=6) #等同于 obj.__call__()
print(res) #__call__ 触发了

# 结果展示:
'''
====> (1, 2, 3) {'a': 4, 'b': 5, 'c': 6}
'''
# 总结:
'''
对象() --->类的__call__
类() ----->自定义元类内的__call__
自定义元类() ---->内置元类(type)的__call__
'''

案例:我们可以通过改写__ call __的逻辑从而控制调用StanfordTeacher的过程,比如将StanfordTeacher的对象的所有属性都变成私有的

class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
    def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
        #1、调用__new__产生一个空对象obj
        obj=self.__new__(self) # 此处的self是类StanfordTeacher,必须传参,代表创建一个StanfordTeacher的对象obj

        #2、调用__init__初始化空对象obj
        self.__init__(obj,*args,**kwargs)

        # 在初始化之后,obj.__dict__里就有值了  将属性变成私有的,即隐藏属性
        obj.__dict__={'_%s__%s' %(self.__name__,k):v for k,v in obj.__dict__.items()}
        #3、返回初始化好的对象obj
        return obj

class StanfordTeacher(object,metaclass=Mymeta):
    school='Stanford'

    def __init__(self,name,age):
        self.name=name
        self.age=age

    def say(self):
        print('%s says welcome to the Stanford to learn Python' %self.name)

t1=StanfordTeacher('lili',18)
print(t1.__dict__) #{'_StanfordTeacher__name': 'lili', '_StanfordTeacher__age': 18}

六 自定义元类控制类的调用

控制类的调用即是控制类的对象的产生

1、自定义元类

class Mymeta(type): #只有及继承了type 类的类才是元类
    def __call__(self, *args, **kwargs):
        print('--->', self.__name__)  # ---> People
        #1、Mymeta.__call__函数内部会先调用 People 内的__new__
        people_obj= self.__new__(self, *args, **kwargs) #得到一个空对象,此处的self是People类
        # 查看初始化前的的对象的属性
        print('people对象初始化前的属性:', people_obj.__dict__)  # {}

        #2、Mymeta.__call__函数会调用 People 内的__init__ 初始化对象
        self.__init__(people_obj, *args, **kwargs) #初始化空对象
        #查看初始化后对象的属性
        print('people对象初始化后的属性:', people_obj.__dict__)  # {'name': 'egon', 'age': 18}

        people_obj.__dict__['xxxxx'] = 11111
        # 3、Mymeta.__call__函数内会返回一个初始化好的对象
        return people_obj

2、类的产生

People = Mymeta() ---> type.__ call __ ==>干了3件事
1、type.__ call __ 函数内会先调用 Mymeta内的 __ new__
2、type.__ call __ 函数内会再调用Mymetan内的 __ init__
3、type.__ call__函数内会返回一个初始化好的对象

lass People(metaclass= Mymeta):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self):
        print('%s:%s' % (self.name, self.age))

    def __new__(cls, *args, **kwargs):
        #产生真正的people_obj对象
        return object.__new__(cls)  #调用父类的__new__方法产生空对象

3、类的调用

obj = People('egon', 18) ==> Mymeta.__ call __ ===>干了3件事
1、Mymeta.__ call __ 函数内会先调用People内的 __ new__
2、Mymeta. __ call__ 函数内会调用People内的 __ init__
3、Mymeta.__ call __函数会返回一个初始化好的对象

obj1=People('egon',18)
obj2=People('egon',18)
print(obj1.__dict__) #{'name': 'egon', 'age': 18, 'xxxxx': 11111}
print(obj2.__dict__) #{'name': 'egon', 'age': 18, 'xxxxx': 11111}

七 属性查找

我们用class自定义的类也全都是对象(包括object类本身也是元类type的 一个实例,可以用type(object)查看)。

属性查找的原则:对象----》类------》父类

注:父类不是元类

属性查找应该分成两层,一层是对象层(基于c3算法的MRO)的查找,另外一个层则是类层(即元类层)的查找

1)类的属性查找,可以找到元类

2)对象的属性查找,找不到元类

class Mymeta(type):  #只有及继承了type 类的类才是元类
    n=444

    def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
        obj=self.__new__(self) # StanfordTeacher.__new__
        # obj=object.__new__(self)
        print(self.__new__ is object.__new__) #True
        self.__init__(obj,*args,**kwargs)
        return obj

class Bar(object):
    # n=333

    # def __new__(cls, *args, **kwargs):
    #  		print('Bar.__new__')
    #     return object.__new__(cls)

class Foo(Bar):
    # n=222
    # def __new__(cls, *args, **kwargs):
    #     print('Foo.__new__')
    pass

class StanfordTeacher(Foo,metaclass=Mymeta):
    # n=111

    def __init__(self,name,age):
        self.name=name
        self.age=age


obj=StanfordTeacher('lili',18)
print(obj.__dict__) #{'name': 'lili', 'age': 18}
# print(obj.n) #报错
print(StanfordTeacher.n) #444
#类的属性查找,可以找到元类
print(StanfordTeacher.n) #自下而上依次注释各个类中的n=xxx,然后重新运行程序,发现n的查找顺序为StanfordTeacher->Foo->Bar->object->Mymeta->type

#对象的属性查找,找不到元类
print()

案例二:

class Mymeta(type):  #只有及继承了type 类的类才是元类
    n=444

    def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
        obj=self.__new__(self) # StanfordTeacher.__new__ 继承了Bar的__new__方法
        # obj=object.__new__(self)
        print(self.__new__) ##<function Bar.__new__ at 0x107a9f1e0>
        print(self.__new__ is object.__new__) #False
        self.__init__(obj,*args,**kwargs)
        return obj

class Bar(object):
    # n=333

    def __new__(cls, *args, **kwargs):
        print(cls.__new__) #<function Bar.__new__ at 0x107a9f1e0>
        print('Bar.__new__')
        return object.__new__(cls)

class Foo(Bar):
    # n=222
    # def __new__(cls, *args, **kwargs):
    #     print('Foo.__new__')
    pass

class StanfordTeacher(Foo,metaclass=Mymeta):
    # n=111

    def __init__(self,name,age):
        self.name=name
        self.age=age


obj=StanfordTeacher('lili',18)
print(obj.__dict__) #{'name': 'lili', 'age': 18}
# print(obj.n) #报错 ,找不到元类
print(StanfordTeacher.n) #444  可以找到元类
#属性查找顺序:StanfordTeacher->Foo->Bar->object->Mymeta->type

通过自定义元类产生的类的属性查找

image-20200415221845760

分析元类 Mymeta 中__ call __ 里的 self. __ new __的查找

class Mymeta(type): 
    n=444

    def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
        obj=self.__new__(self)
        print(self.__new__ is object.__new__) #True


class Bar(object):
    n=333

    # def __new__(cls, *args, **kwargs):
    #     print('Bar.__new__')

class Foo(Bar):
    n=222

    # def __new__(cls, *args, **kwargs):
    #     print('Foo.__new__')

class StanfordTeacher(Foo,metaclass=Mymeta):
    n=111

    school='Stanford'

    def __init__(self,name,age):
        self.name=name
        self.age=age

    def say(self):
        print('%s says welcome to the Stanford to learn Python' %self.name)


    # def __new__(cls, *args, **kwargs):
    #     print('StanfordTeacher.__new__')


StanfordTeacher('lili',18) #触发StanfordTeacher的类中的__call__方法的执行,进而执行self.__new__开始查找

总结:

Mymeta下的__ call __ 里的self.__ new __ 在StanfordTeacher、Foo、Bar里都没有找到 __ new __ 的情况下,会去找object里的 __ new __ ,而object下默认就有一个 __ new __ ,所以即便是之前的类均未实现 __ new __ ,也一定会在object中找到一个,根本不会、也根本没必要再去找元类Mymeta->type中查找 __ new__

在元类的__ call __ 中是可以用object.__ new__ (self)去造对象,但是还是推荐在 __ call __ 中使用self. __ new __ (self)去创造空对象,因为这种方式会检索三个类StanfordTeacher->Foo->Bar,而object. __ new __则是直接跨过了他们三个

练习:

1、在元类中控制把自定义类的数据属性都变成大写

​ 知识点:

​ callable() 函数用于检查一个'对象'是否是可以调用的。
​ 如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。

class Mymetaclass(type):
    def __new__(cls,name,bases,attrs):
        # print(cls) #<class '__main__.Mymetaclass'>
        update_attrs={}
        # print(attrs)  #{'__module__': '__main__', '__qualname__': 'Chinese',
        # 'country': 'China', 'tag': 'Legend of the Dragon', 'walk': <function Chinese.walk at 0x10d21c1e0>}

        for k,v in attrs.items():
            if not callable(v) and not k.startswith('__'):
                update_attrs[k.upper()]=v
            else:
                update_attrs[k]=v
        obj = type.__new__(cls,name,bases,update_attrs)
        print(obj.__dict__)

        return obj


class Chinese(metaclass=Mymetaclass):
    country='China'
    tag='Legend of the Dragon' #龙的传人
    def __init__(self, name):
        self.name = name
    def walk(self):
        print('%s is walking' %self.name)


    def __str__(self):
        return '1111'
print(Chinese.__dict__) #查看类的属性

obj = Chinese('egon')
print(obj)              #1111
print(obj.walk())     #egon is walking

'''
{'__module__': '__main__',
 'COUNTRY': 'China',
 'TAG': 'Legend of the Dragon',
 'walk': <function Chinese.walk at 0x0000000001E7B950>,
 '__dict__': <attribute '__dict__' of 'Chinese' objects>,
 '__weakref__': <attribute '__weakref__' of 'Chinese' objects>,
 '__doc__': None}
'''

2、在元类中控制自定义的类无需__ init __方法

# 1、元类帮其完成创建对象,以及初始化操作
# 2、要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument
# 3、key作为用户自定义类产生对象的属性,且所有属性变成大写
class Mymeta(type):
    def __call__(self, *args, **kwargs):
        print(self) #<class '__main__.Chinese'>
        print(args) #()
        print(kwargs) #{'name': 'lili', 'age': 18, 'sex': 'male'}
        if args:
            raise TypeError('must user keyword argument for key function')
        obj = object.__new__(self) #创建对象,self 为类 Chinese
        for k, v in kwargs.items():
            obj.__dict__[k.upper()] = v
        return obj

class Chinese(metaclass=Mymeta):
    country = 'China'
    tag = 'Legend of the Dragon'  # 龙的传人

    def walk(self):
        print('%s is walking' % self.name)

p = Chinese(name='lili', age=18, sex='male')
print(p.__dict__) #{'NAME': 'lili', 'AGE': 18, 'SEX': 'male'}

3、在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性

方式一:

class Mymeta(type):
    def __call__(self, *args, **kwargs):
        # print(self.__name__) #Foo
        attr= {} #定义一个的空字典
        obj = object.__new__(self)
        self.__init__(obj, *args, **kwargs)
        # print(obj.__dict__) #{'name': 'egon', 'age': 18, 'sex': 'female'}
        for k, v in obj.__dict__.items():
            k1 = '_%s__%s'%(self.__name__, k)
            attr[k1] = v
        obj.__dict__ = attr
        return obj


class Foo(object,metaclass=Mymeta):  # Foo=Mymeta(...)
    def __init__(self, name, age,sex):
        self.name=name
        self.age=age
        self.sex=sex


p= Foo('egon', 18, 'female')
print(p.__dict__) #{'_Foo__name': 'egon', '_Foo__age': 18, '_Foo__sex': 'female'}

方式二:

class Mymeta(type):
    #定义类触发
    def __init__(self,class_name,class_bases,class_dic):
        #控制类Foo的创建
        print('__init__执行了')
        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

    #调用类时触发
    def __call__(self, *args, **kwargs):
        print('__call__执行了')
        #控制Foo的调用过程,即Foo对象的产生过程
        obj = self.__new__(self,*args, **kwargs)
        self.__init__(obj, *args, **kwargs)
        obj.__dict__={'_%s__%s' %(self.__name__,k):v for k,v in obj.__dict__.items()}

        return obj

class Foo(object,metaclass=Mymeta):  # Foo=Mymeta(...)
    def __init__(self, name, age,sex):
        self.name=name
        self.age=age
        self.sex=sex


obj=Foo('lili',18,'male')
print(obj.__dict__) #{'_Foo__name': 'lili', '_Foo__age': 18, '_Foo__sex': 'male'}

#结果展示:
'''
__init__执行了
__call__执行了
{'_Foo__name': 'lili', '_Foo__age': 18, '_Foo__sex': 'male'}
'''

4、基于元类实现单例模式

单例:即单个实例,指的是同一个类实例化多次的结果指向同一个对象,用于节省内存空间

如果我们从配置文件中读取配置来进行实例化,在配置相同的情况下,就没必要重复产生对象浪费内存了

#settings.py文件内容如下
HOST='1.1.1.1'
PORT=3306

#方式一:定义一个类方法实现单例模式
import settings

class Mysql:
    __instance=None
    def __init__(self,host,port):
        self.host=host
        self.port=port

    @classmethod
    def singleton(cls):
        if not cls.__instance:
            cls.__instance=cls(settings.HOST,settings.PORT)
        return cls.__instance

obj1=Mysql('1.1.1.2',3306)
obj2=Mysql('1.1.1.3',3307)
print(obj1 is obj2) #False

obj3=Mysql.singleton()
obj4=Mysql.singleton()
print(obj3 is obj4) #True


#方式二:定制元类实现单例模式
import settings

class Mymeta(type):
    def __init__(self,name,bases,dic): #定义类Mysql时就触发
        # 事先先从配置文件中取配置来造一个Mysql的实例出来
        self.__instance = object.__new__(self)  # 产生对象
        self.__init__(self.__instance, settings.HOST, settings.PORT)  # 初始化对象
        # 上述两步可以合成下面一步
        # self.__instance=super().__call__(*args,**kwargs)
        super().__init__(name,bases,dic)

    def __call__(self, *args, **kwargs): #Mysql(...)时触发
        if args or kwargs: # args或kwargs内有值
            obj=object.__new__(self)
            self.__init__(obj,*args,**kwargs)
            return obj
        return self.__instance

class Mysql(metaclass=Mymeta):
    def __init__(self,host,port):
        self.host=host
        self.port=port

obj1=Mysql() # 没有传值则默认从配置文件中读配置来实例化,所有的实例应该指向一个内存地址
obj2=Mysql()
obj3=Mysql()
print(obj1 is obj2 is obj3)
obj4=Mysql('1.1.1.4',3307)


#方式三:定义一个装饰器实现单例模式
import settings

def singleton(cls): #cls=Mysql
    _instance=cls(settings.HOST,settings.PORT)

    def wrapper(*args,**kwargs):
        if args or kwargs:
            obj=cls(*args,**kwargs)
            return obj
        return _instance
    return wrapper


@singleton # Mysql=singleton(Mysql)
class Mysql:
    def __init__(self,host,port):
        self.host=host
        self.port=port

obj1=Mysql()
obj2=Mysql()
obj3=Mysql()
print(obj1 is obj2 is obj3) #True

obj4=Mysql('1.1.1.3',3307)
obj5=Mysql('1.1.1.4',3308)
print(obj3 is obj4) #False
posted @ 2020-04-15 23:33  蛋蛋的丶夜  阅读(93)  评论(0编辑  收藏  举报