什么是"1 ..__ truediv__"? Python是否具有..(“点点")表示法语法? [英] What is `1..__truediv__` ? Does Python have a .. ("dot dot") notation syntax?

查看:181
本文介绍了什么是"1 ..__ truediv__"? Python是否具有..(“点点")表示法语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一种语法,这是我学习python之前从未见过的,在大多数教程中,..表示法看起来像这样:

I recently came across a syntax I never seen before when I learned python nor in most tutorials, the .. notation, it looks something like this:

f = 1..__truediv__ # or 1..__div__ for python 2

print(f(8)) # prints 0.125 

我认为它与(完全一样,只是更长)完全相同:

I figured it was exactly the same as (except it's longer, of course):

f = lambda x: (1).__truediv__(x)
print(f(8)) # prints 0.125 or 1//8

但是我的问题是:

  • 它如何做到这一点?
  • 两个点实际上意味着什么?
  • 如何在更复杂的语句中使用它(如果可能)?

这将来可能会节省很多代码...:)

This will probably save me many lines of code in the future...:)

推荐答案

您所拥有的是float文字,不带尾随零,然后您可以使用该字面量的__truediv__方法.它本身不是运算符;它不是运算符.第一个点是float值的一部分,第二个点是用于访问对象属性和方法的点运算符.

What you have is a float literal without the trailing zero, which you then access the __truediv__ method of. It's not an operator in itself; the first dot is part of the float value, and the second is the dot operator to access the objects properties and methods.

您可以通过执行以下操作来达到相同的目的.

You can reach the same point by doing the following.

>>> f = 1.
>>> f
1.0
>>> f.__floordiv__
<method-wrapper '__floordiv__' of float object at 0x7f9fb4dc1a20>

另一个例子

>>> 1..__add__(2.)
3.0

在这里,我们将1.0加到2.0,显然得出3.0.

Here we add 1.0 to 2.0, which obviously yields 3.0.

这篇关于什么是"1 ..__ truediv__"? Python是否具有..(“点点")表示法语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆