Python类和元类

深入理解类

 

1.类也是一个对象,但具有创建其自身实例的能力

2.类可以和一个变量进行绑定

3.你可以为类增加属性

4.你可以把它作为函数的参数传递

 

例如:

 

Python1.png 

 

 


元类

 

1.类的创建和管理者(type)

 

例如:

 

Python2.png 

 

2.所有的类都是元类(type)的实例

 

例如:

 

Python0.png 

 

3.类实例化过程

 

1)_new_()

2)_init_()

 

程序演示:  

      10_instance.py

      class Custom:

    def __init__(self):

        print('Init method.')

 

    def __new__(cls,*args,**kwargs):

        print('New Instance.')

        return object.__new__(cls,*args,**kwargs)

 

if __name__ == '__main__':

    Custom()

            

程序的运行结果为:

 

Python3.png 

 

4.自定义元类

 

1)目的:对其创建的类进行预处理

2)继承type

3)定义_new_()方法

4)还可以定义_init_()方法

 

程序演示:

       cus_type.py

       class MyMeta(type):

    def __init__(self,name,bases,dicts):

        print('Init Instance.')

 

    def __new__(cls,name,bases,dicts):

        dicts['info'] = lambda self:print('Djx.')

        res = type.__new__(cls,name,bases,dicts)

        res.company = 'MaiZi'

        return res

 

class custom(metaclass=MyMeta):

    pass

 

if __name__ == '__main__':

    cus = custom()

    cus.info()

    print(cus.company)

 

class cus:

    __metaclass__ = MyMeta

    pass

 

__metaclass__ = MyMeta

 

程序的运行结果为:

 

Python4.png 

 

5.应用元类

 

1)Python 3.0

a.类继承中提供关键字参数:metaclass=元类名

2)Python 2.0

a.定义一个模块级变量_metaclass_=元类名;

b.为某个类添加类属性_metaclass_=元类名。

 

 

【本文由麦子学院独家原创,转载请注明出处并保留原文链接】

posted @ 2019-07-20 10:19  天涯海角路  阅读(160)  评论(0)    收藏  举报