zoukankan      html  css  js  c++  java
  • python学习之元类

    class Foo:
    pass

    f=Foo()
    print(type(f1)) #f1是通过Foo类实例化的对象
    print(type(Foo)) #Foo是通过type类实例化的对象
    print('===================>')

    class Foo1:
    x=1
    def __init__(self,name,age):
    self.name=name
    self.age=age

    def test(self):
    pass

    print(Foo1.__dict__)

    f1=Foo1('mcc',11)

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

    def test(self):
    print("=========>")
    Foo2=type('Foo2',(object,),{'x':1,'__init__':__init__,'test':test})

    print(Foo2.__dict__)
    f2=Foo2('zcc',12)

    元类type实例化(Foo,Foo1,Foo2)三个对象,同时这三个类又分别实例化(f,f1,f2)三个对象
    实际应用:
    class MyType(type):
       def __init__(self,a,b,c):
    pass
    # print(a)
    # print(b)
    # print(c)
    def __call__(self, *args, **kwargs):
    print('====>')
    print(self)
    obj=object.__new__(self)
    self.__init__(obj,*args,**kwargs)
    return obj

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

    f3=Foo('alan',12)
    print(f3.__dict__)


  • 相关阅读:
    Module:template
    Grunt:GruntFile.js
    Grunt:常见错误
    架构:架构-1
    架构:目录
    DS:template
    Jasper:用户指南 / 设备 / 生命周期管理 / SIM 卡状态
    Jasper-Api:接口测试
    linux服务之git
    Java实现 洛谷 P1487 陶陶摘苹果(升级版)
  • 原文地址:https://www.cnblogs.com/jinpingzhao/p/12920764.html
Copyright © 2011-2022 走看看