This question already has an answer here:
Special (magic) methods in Python [closed]
                                
                                    (1个答案)
                                
                        
                                5年前关闭。
            
                    
我是python编程的新手,现在我到达了Python书籍中有关OOP的部分。我对python类中的方法定义感到困惑。

之间有什么区别?

def __add__(self):
  pass




def add(self):
  pass


如果您能为我澄清一下,我将不胜感激。感谢大伙们。

最佳答案

以下划线开头和结尾的方法(例如__add__(...))可用于覆盖现有功能,而没有下划线的add(...)方法是新的用户定义方法。区别是:

使用__add__(self),您可以调用
    thisObj + otherObj

使用add(self),您可以致电
    thisObj.add(otherObj)

因此,__add____sub____call__等会覆盖现有的运算符或功能。

10-08 06:02
查看更多