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


  • 相关阅读:
    1、Python的初识与简介
    解密解密
    python看是32位还是64
    linux实战一段,安装python3(centos)
    前段技巧
    django后端safe和前端safe的方法
    测试
    python小知识整理
    ajax格式
    111
  • 原文地址:https://www.cnblogs.com/jinpingzhao/p/12920764.html
Copyright © 2011-2022 走看看