算术运算符
类型工厂函数,指的是“不通过类而是通过函数来创建对象”。
【例子】
1
class C:
2
pass
3
4
5
print(type(len)) # <class 'builtin_function_or_method'>
6
print(type(dir)) # <class 'builtin_function_or_method'>
7
print(type(int)) # <class 'type'>
8
print(type(list)) # <class 'type'>
9
print(type(tuple)) # <class 'type'>
10
print(type(C)) # <class 'type'>
11
print(int('123')) # 123
12
13
# 这个例子中list工厂函数把一个元祖对象加工成了一个列表对象。
14
print(list((1, 2, 3))) # [1, 2, 3]
<class 'builtin_function_or_method'> <class 'builtin_function_or_method'> <class 'type'> <class 'type'> <class 'type'> <class 'type'> 123 [1, 2, 3]
__add__(self, other)
定义加法的行为:+
__sub__(self, other)
定义减法的行为:-
【例子】
1
class MyClass:
2
3
def __init__(self, height, weight):
4
self.height = height
5
self.weight = weight
6
7
# 两个对象的长相加,宽不变.返回一个新的类
8
def __add__(self, others):
9
return MyClass(self.height + others.height, self.weight + others.weight)
10
11
# 两个对象的宽相减,长不变.返回一个新的类
12
def __sub__(self, others):
13
return MyClass(self.height - others.height, self.weight - others.weight)
14
15
# 说一下自己的参数
16
def intro(self):
17
print("高为", self.height, " 重为", self.weight)
18
19
20
def main():
21
a = MyClass(height=10, weight=5)
22
a.intro()
23
24
b = MyClass(height=20, weight=10)
25
b.intro()
26
27
c = b - a
28
c.intro()
29
30
d = a + b
31
d.intro()
32
33
34
if __name__ == '__main__':
35
main()
36
37
# 高为 10 重为 5
38
# 高为 20 重为 10
39
# 高为 10 重为 5
40
# 高为 30 重为 15
高为 10 重为 5 高为 20 重为 10 高为 10 重为 5 高为 30 重为 15
__mul__(self, other)
定义乘法的行为:*
__truediv__(self, other)
定义真除法的行为:/
__floordiv__(self, other)
定义整数除法的行为://
__mod__(self, other)
定义取模算法的行为:%
__divmod__(self, other)
定义当被divmod()
调用时的行为divmod(a, b)
把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
。