zoukankan      html  css  js  c++  java
  • Python基础第23天

    一:元类  metaclass

    class Foo:
        pass
    
    f1=Foo()
    print(type(f1))
    print(type(Foo))   #<class 'type'>类的类就是type

    1、 什么是元类?

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

    元类是用来控制如何创建类的,正如类是创建对象的模板一样

    元类的实例为类,正如类的实例为对象(f1对象是Foo类的一个实例Foo类是 type 类的一个实例)

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

    2、 创建类的两种方式

    方式一:

    1 class Foo:
    2     def func(self):
    3         print('from func')

    方式二:type 方式生成,type实例化的结果

    1 def func(self):
    2         print('from func')
    3 x=1
    4 Foo=type('Foo',(object,),{'func':func,'x':1})

    3、自定制元类:

    class Mytype(type):
        def __init__(self,a,b,c):
            print('元类的构造函数执行')
            # print(a)
            # print(b)
            # print(c)
        def __call__(self, *args, **kwargs):
            print('=============')
            obj=object.__new__(self)
            self.__init__(obj,*args, **kwargs)  #Foo.__init__
            return obj
    
    class Foo(metaclass=Mytype): #Mytype()4个参数=====》__init__
        def __init__(self,name):
            self.name=name
    
    f1=Foo('laex')
    print(f1)
    print(f1.__dict__)
  • 相关阅读:
    API接口:分页
    PHP中判断变量为空的几种方法
    获取APP最新版本的接口案例
    浏览器兼容性
    APP的消息推送(极光推送)
    Json
    PHP 图片上传 (AIP图片上传接口)
    日历时间插件
    PHP读写文件
    ThinkPHP 事务处理 (事务回滚) 、异常处理
  • 原文地址:https://www.cnblogs.com/xyd134/p/6580840.html
Copyright © 2011-2022 走看看