猿问

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

classobject:
"""Themostbasetype"""
...
@staticmethod#knowncaseof__new__
def__new__(cls,*more):#knownspecialcaseofobject.__new__
"""Createandreturnanewobject.Seehelp(type)foraccuratesignature."""
pass
...
这里的__new__方法很奇怪,下面不是第一个参数还绑定了类(也就是源对象object自身)吗?
我的问题有几个:
为什么不是类方法?
这是个静态方法装饰器的特例吗?
除了object里面,还有别的地方这么用吗?
期待大家解答
DIEA
浏览 997回答 2
2回答

侃侃无极

想通了,现列出个人的看法作为python的源对象,object是所有类对象的祖先(base)包括另一个源对象type。其实__new__方法的第一个参数只是恰好设置成了cls,并非要绑定某个实例对象,所以可以这么回答是静态方法,因为__new__()在这里只是一个绑定源对象object的普通方法,常规意义下__new__()的确是类方法不是,所有的静态方法都只是绑定类对象或者实例对象的普通方法没有,实际上是把cls这个普通的positionargument和类方法当中的代表类对象的clspositionargument混淆了需要补充的是,源对象类型的实例也是类,是可以进一步实例化的,常常作为某些框架的基础数据类型描述符,可以进行强制类型检查,比如django的ORM的ModelBase,作为metaclass被所有model继承,涉及元编程的一些东西附上官方文档的解释,以及stackoverflow一些对这个东西的讨论,很清晰,看来还是多看官方文档更有用1.documentationobject.__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的讨论
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答