python的__new__是类方法嘛_为什么__new__在Python新式类中不是类方法?

__new__是静态方法允许一个用例当你创建一个子类的实例:

return super(, cls).__new__(subcls, *args, **kwargs)

如果new是一个类方法,则上面的写为:

return super(, cls).new(*args, **kwargs)

并且没有地方放置subcls。

I don’t really see when that would be a proper use of __new__, though. Maybe I’m not seeing it, but that just seems to me to be a completely pathological use of it (and it should be said, that if you still really want it, then you could access it with object.__new__.__func__). At the very least, I find it very hard to imagine that it would have been the reason for Guido to change __new__ from being a class method to a static method.

class Base(object):

@classmethod

def new(cls):

print("Base.new(%r)" % (cls,))

return cls()

class UseSuper(Base):

@classmethod

def new(cls):

print("UseSuper.new(%r)" % (cls,))

return super(UseSuper, cls).new() # passes cls as the first arg

class NoSuper(Base):

@classmethod

def new(cls):

print("NoSuper.new(%r)" % (cls,))

return Base.new() # passes Base as the first arg

class UseFunc(Base):

@classmethod

def new(cls):

print("UseFunc.new(%r)" % (cls,))

return Base.new.im_func(cls) # or `.__func__(cls)`. # passes cls as the first arg

print(UseSuper.new())

print('-'*60)

print(NoSuper.new())

print('-'*60)

print(UseFunc.new())

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值