zoukankan      html  css  js  c++  java
  • day07_09 metaclass创建一个类

    __author__ = "Alex Li"
    
    
    class MyType(type):
        def __init__(self, what, bases=None, dict=None):
            print("--MyType init---")
            super(MyType, self).__init__(what, bases, dict)
    
        def __call__(self, *args, **kwargs):
            print("--MyType call---")
    
            obj = self.__new__(self, *args, **kwargs)
            obj.data = {"name":111}
            self.__init__(obj, *args, **kwargs)
    
    
    class Foo(object):
    
        __metaclass__ = MyType
    
        def __init__(self, name):
            self.name = name
            print("Foo ---init__")
    
        #默认自带方法__new__于__init__之前执行,用于创建实例(不用写)
        def __new__(cls, *args, **kwargs):
            print("Foo --new--")
            print(object.__new__(cls))
            return object.__new__(cls) #继承父亲的__new__方法
    
    
    
    # 第一阶段:解释器从上到下执行代码创建Foo类
    # 第二阶段:通过Foo类创建obj对象
    obj = Foo("Alex")
    print(obj.name)
    
  • 相关阅读:
    python高级 之(三) --- 高阶函数
    python高级 之(二) --- 类装饰器
    python高级 之(一) --- 函数类型
    jQuery
    css
    html
    px2rem
    keep-alive标签
    rem适配方案2(flexible.js)
    媒体查询
  • 原文地址:https://www.cnblogs.com/netflix/p/14855016.html
Copyright © 2011-2022 走看看