python 之 __new__ 方法理解

python的new方法 使用场景不同效果也不一样
一种是指定元类时候, metaclass=MyType 类型
这种方式 在解释器执行到 metaclass=CrawlerProxyMetaclass
的时候, __new__方法就开始执行!
这里的 __new__方法是用来创建类对象的

class CrawlerProxyMetaclass(type):
    def __new__(cls, classname, parentclass, attrs):
        attrs['__crawl_method__'] = []
        print('in method new ')
        count = 0
        for key, value in attrs.items():
            if key.startswith('crawl_'):
                attrs['__crawl_method__'].append(key)
                count += 1
        attrs['__crawl_method_count__'] = count
        return super().__new__(cls, classname, parentclass, attrs)
        #return type.__new__(cls, classname, parentclass, attrs)

一种普通普通的继承关系 调用父类的__new__方法
这里的__new__方法是用来创建对象实例的
创建对象的时候才会被调用
先看object的 __new__方法

@staticmethod # known case of __new__
    def __new__(cls, *more): # known special case of object.__new__
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

我们重写父类的 __new__方法时候可以

    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)