能够从官网上找到:
http://docs.python.org/3/reference/datamodel.html#specialnames
下面列一些经常使用的:
用一个实例来介绍:html
""" File: student.py Resources to manage a student's name and test scores. """ class Student(object): """represents a student""" count = 0 def __init__(self, name, number): """Constructor creates a Student with the given name and number of scores and sets all scores to 0.""" Student.count += 1 self.name = name self.scores = [] for count in range(number): self.scores.append(0) def __eq__(self, other): if self is other: return True if type(self) != type(other): return False return self.name == other.name and self.scores == other.scores def __str__(self): """Returns the string representation of the student""" return 'Name:' + self.name + '\nScores:' + \ ' '.join(map(str, self.scores)) def __add__(self, other): if isinstance(other, Point): self.count += other.count return self.__str__() else: self.count += other return self.__str__() def __radd__(self, other): return self.__add__(other) def __gt__(self, other): if self.count > other: return True return False def __call__(self): print("Now what you saw was exactly the function of __call__()")
__eq__()实现的是运算符号==的功能, 比较的步骤是这样的:设有两个对象a, b 首先看两个对象的引用是否相等,若是相等,则a == b为True;不相等继续下一步骤: 看看两个对象是不是同一类型,即type(a) == type(b), 若是不是,则a==b为False;不相等继续下一步骤; 看看两个对象的值是否相等,即a.value==b.value,若是是,则a==b为True;不等就是False。 __str__()实现的是print(a),它决定了你调用print()函数的时候会输出什么, 可是要注意的是,这个函数只能返回字符串,不能是其余的内容。 __add__()实现的是a + b,经过更改它的内容,你能够实现print(a, 12)和print(a, b)的功能。 __radd__()实现的是补充__add__(),好比我要实现print(12 + a),也就是12 位于左边,__radd__()的用法见上方代码。 __sub__()实现的是a - b,__rsub__()实现的是补充__sub__(),和add相似。 一样,mul/rmul -> 乘法; div/rdiv -> 除法; __gt__()实现的是a > b;__lt__()实现的是a < b __repr__()的做用和__str__()类似,能够通用不用搞那么细, 若是想弄懂它们以前的区别,能够查看这篇博客:
https://blog.csdn.net/weixin_42615068/article/details/89093671python
__call__()实现的是:a(),(a是一个Student实例) 直接将类变量加上括号运行默认为执行类中的__call__函数