metaclass元类

一 元类

元类是类的类,是类的模板

元类是用来控制如何创建类的,正如类是创建对象的模板一样,而元类的主要目的是为了控制类的创建行为

元类的实例化的结果为我们用class定义的类,正如类的实例为对象(f1对象是Foo类的一个实例Foo类是 type 类的一个实例)

type是python的一个内建元类,用来直接控制生成类,python中任何class定义的类其实都是type类实例化的对象

 二 创建类的两种方式

方式一:使用class关键字

class A(object):
    pass

print(type(A))   #<class 'type'>

方式二:手动模拟class创建类的过程

def run(self):
    print('%s is runing' %self.name)

class_name = 'Bar'
bases = (object,)
class_dic={
    'x':1,
    'run':run
}

Bar = type(class_name,bases,class_dic)
print(Bar) print(type(Bar))

参数格式:

type(class_name,bases,dic)

要动态创建一个class对象,type()函数依次传入3个参数:

1、class的名称,字符串形式;
2、继承的父类集合,注意Python支持多重继承,如果只有一个父类,注意tuple的单元素写法;
3、{k:v} 或者 dict(k=v)

例一:

class Foo(object):
    class Meta:
        model = 'qwer'


由type创建:
_meta = type('Meta',(object,),{'model':'qwer'})
Foo = type('Foo',(object,),{'Meta':'_meta'})
View Code

例二:

老规矩,来个熟悉的:

class Hello(object):

    def hw(self,name='World'):
        print('Hello,%s'%name)
        

h = Hello()
h.hw()

print(type(Hello))
print(type(h))


#输出结果:
# Hello,World
# <class 'type'>
# <class '__main__.Hello'>
View Code

再换个:

def func(self,name='World'):
    print('Hello,%s'%name)

Hello = type('Hello',(object,),{'hw':func})

h = Hello()
h.hw()


print(type(Hello))
print(type(h))


#数据结果:
    # Hello,World
    # <class 'type'>
    # <class '__main__.Hello'>
    
    
#注释:class的方法名称与函数绑定,这里我们把函数func绑定到方法名hw上。
View Code

三 自定义元类:

class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        pass

    def __call__(self, *args, **kwargs):
        # print('这里的self:',self)

        obj = self.__new__(self)
        self.__init__(obj,*args,**kwargs)
        return obj

class Foo(metaclass=Mymeta):
    x = 123

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

    def run(self):
        'run function'
        print('runing')

# print(Foo.__dict__)

f = Foo('Tom')
print(f.name)
View Code
原文地址:https://www.cnblogs.com/zhaochangbo/p/7717234.html