为了账号安全,请及时绑定邮箱和手机立即绑定

关于python源对象object的__new__(),为什么是静态方法?

关于python源对象object的__new__(),为什么是静态方法?

DIEA 2019-05-09 22:19:56
classobject:"""Themostbasetype"""...@staticmethod#knowncaseof__new__def__new__(cls,*more):#knownspecialcaseofobject.__new__"""Createandreturnanewobject.Seehelp(type)foraccuratesignature."""pass...这里的__new__方法很奇怪,下面不是第一个参数还绑定了类(也就是源对象object自身)吗?我的问题有几个:为什么不是类方法?这是个静态方法装饰器的特例吗?除了object里面,还有别的地方这么用吗?期待大家解答
查看完整描述

2 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

想通了,现列出个人的看法
作为python的源对象,object是所有类对象的祖先(base)包括另一个源对象type。其实__new__方法的第一个参数只是恰好设置成了cls,并非要绑定某个实例对象,所以可以这么回答
是静态方法,因为__new__()在这里只是一个绑定源对象object的普通方法,常规意义下__new__()的确是类方法
不是,所有的静态方法都只是绑定类对象或者实例对象的普通方法
没有,实际上是把cls这个普通的positionargument和类方法当中的代表类对象的clspositionargument混淆了
需要补充的是,源对象类型的实例也是类,是可以进一步实例化的,常常作为某些框架的基础数据类型描述符,可以进行强制类型检查,比如django的ORM的ModelBase,作为metaclass被所有model继承,涉及元编程的一些东西
附上官方文档的解释,以及stackoverflow一些对这个东西的讨论,很清晰,看来还是多看官方文档更有用
1.documentation
object.__new__(cls[,...])
Calledtocreateanewinstanceofclasscls.__new__()isastaticmethod(special-casedsoyouneednotdeclareitassuch)thattakestheclassofwhichaninstancewasrequestedasitsfirstargument.Theremainingargumentsarethosepassedtotheobjectconstructorexpression(thecalltotheclass).Thereturnvalueof__new__()shouldbethenewobjectinstance(usuallyaninstanceofcls).Typicalimplementationscreateanewinstanceoftheclassbyinvokingthesuperclass’s__new__()methodusingsuper().__new__(cls[,...])withappropriateargumentsandthenmodifyingthenewly-createdinstanceasnecessarybeforereturningit.
If__new__()returnsaninstanceofcls,thenthenewinstance’s__init__()methodwillbeinvokedlike__init__(self[,...]),whereselfisthenewinstanceandtheremainingargumentsarethesameaswerepassedto__new__().
If__new__()doesnotreturnaninstanceofcls,thenthenewinstance’s__init__()methodwillnotbeinvoked.
__new__()isintendedmainlytoallowsubclassesofimmutabletypes(likeint,str,ortuple)tocustomizeinstancecreation.Itisalsocommonlyoverriddenincustommetaclassesinordertocustomizeclasscreation.
2.StackOverflow的讨论
                            
查看完整回答
反对 回复 2019-05-09
  • 2 回答
  • 0 关注
  • 996 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号