使用特殊方法和只定义普通类方法有什么区别?我正在阅读这个网站,其中列出了很多。
例如,它提供了这样的课程。
class Word(str):
'''Class for words, defining comparison based on word length.'''
def __new__(cls, word):
# Note that we have to use __new__. This is because str is an immutable
# type, so we have to initialize it early (at creation)
if ' ' in word:
print "Value contains spaces. Truncating to first space."
word = word[:word.index(' ')] # Word is now all chars before first space
return str.__new__(cls, word)
def __gt__(self, other):
return len(self) > len(other)
def __lt__(self, other):
return len(self) < len(other)
def __ge__(self, other):
return len(self) >= len(other)
def __le__(self, other):
return len(self) <= len(other)
对于这些特殊方法中的每一个,为什么我不能只制作一个普通方法,它们有什么不同?我想我只需要一个我找不到的基本解释,谢谢。