所有专有方法中,__init__()要求无返回值,或者返回 None。而其他方法,如__str__()、__add__()等,一般都是要返回值的,如下所示:
>>>classComplex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
... return'hello'
...
>>> x =Complex(3.0,-4.5)
Traceback(most recent call last):
File"", line 1,in
TypeError: __init__() should returnNone,not'str'
而对于 __str__()、__add__() 等。
def __str__(self):
return'Vector (%d, %d)'%(self.a,self.b)
def __repr__(self):
return'Vector (%d, %d)'%(self.a,self.b)
def __add__(self,other):
if other.__class__ isVector:
returnVector(self.a + other.a,self.b + other.b)
elif other.__class__ isint:
returnVector(self.a+other,self.b)