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


  • 相关阅读:
    查找整数
    Ling To Xml 学习之 对xml增、删、改、查
    JS获得鼠标
    xml之数据岛绑定到表格
    C# 三种序列化[转]
    编程字体
    Oracle 、C#
    提示信息Javascript
    几个好用的日历控件
    收藏网站
  • 原文地址:https://www.cnblogs.com/jinpingzhao/p/12920764.html
Copyright © 2011-2022 走看看