Python // 运算符 – Python 中的楼层除法

Python // 运算符也称为整除运算符。它是Python中的算术运算符之一。它适用于 Python 中的数字。

Python // 运算符

它类似于除法运算符,只不过它返回除法运算的整数部分。因此,如果除法的输出是 3.999,则将返回 3。这就是它被称为底除运算符的原因。

让我们看一下 Python 中楼层划分的一些示例。

1. 整数除法

>>> 10//3
3
>>> 10//2
5

2.用花车进行楼层划分

>>> 10.0//3
3.0
>>> 10//2.0
5.0
>>> 11.99//3.00
3.0

3.复数楼层划分

复数不支持楼层划分。如果我们尝试对复数使用 // 运算符,它将抛出TypeError: can’t take Floor of complex number。

>>> x = 10 + 3j
>>> type(x)
<class 'complex'>
>>> x // 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't take floor of complex number.
>>>

重载 // 运算符

我们知道Python支持运算符重载。如果要支持对象的 // 运算符,则需要重写 __floordiv__(self, other) 方法。让我们看一个重载楼层除法运算符的简单示例。

# Floor Division Operator overloading example
 
class Data:
    id = 0
 
    def __init__(self, i):
        self.id = i
 
    def __floordiv__(self, other):
        print("overloading // operator")
        return self.id // other.id
 
 
d1 = Data(10)
d2 = Data(3)
 
print(d1 // d2)

输出:

概括

  • Python // 运算符适用于数字 – int 和 float。
  • 下取除法运算符返回除法运算的整数部分。
  • 如果被除数和除数都是整数,则下限除法也将返回 int。
  • 如果股息和除数之一是浮动的,则下限除法将返回浮动。
  • 我们不能对复数使用 // 运算符。

下一步是什么?

参考