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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值