這裏我從str類的__new__()方法來講明。spa
str的__new__(cls,*args)必須傳入一個參數cls,他是str的子類(注意不是實例)。blog
__new__()的返回值是該子類的實例,表現爲字符串。字符串
>>> class st(str): ... def __new__(cls,value,title): ... ins = str.__new__(cls,value) ... ins._title = title ... return ins ... def title(self): ... return self._title ... >>> s = st('hello','hi') >>> s 'hello' >>> str.__new__(st,'ok') 'ok' >>> a = str.__new__(st,'ok') >>> type(a) <class '__main__.st'> >>> a 'ok'