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__)


  • 相关阅读:
    。。。
    __new__ 单例
    bokeh
    空间数据可视化
    关系网络图
    Pandas 50题练习
    seaborn
    数据输出及内容美化 简单介绍
    数据分析---项目总结
    数学建模
  • 原文地址:https://www.cnblogs.com/jinpingzhao/p/12920764.html
Copyright © 2011-2022 走看看