这种语法是怎么实现的?

2017-10-12 12:46:33 +08:00
 cevincheung
model.query.filter(model.c.filed1 > model.c.cfiled2).all()

model.c.field1 > model.c.field2 这不是个比较语句么?不是会把结果当成参数传进去么?

4027 次点击
所在节点    Flask
18 条回复
Morriaty
2017-10-12 12:53:15 +08:00
def __gt__(self, other):
if self.data > other.data:
return "condition_string_one"
else:
return "two"
cevincheung
2017-10-12 12:54:12 +08:00
@Morriaty #1

所以像其他的等于、数组、json 都是这样?
guoziyan
2017-10-12 13:19:21 +08:00
scala 会认为是 lambda python 也是这么处理的吗
jakes
2017-10-12 13:44:51 +08:00
操作符重载
xmcp
2017-10-12 13:45:52 +08:00
这应该是这个库的一个语法糖。让__lt__返回一个奇怪的对象传到 filter 里。
jyf
2017-10-12 14:38:47 +08:00
python 的 orm 库里好多这种 都是生成器把戏 这个会重载生成器 然后分析你原始的输入 替换成相应的 sql
raiz
2017-10-12 17:00:38 +08:00
应该是重载运算符,返回一个 callable 对象,filter 函数里回调这个方法吧
northisland
2017-10-12 17:31:52 +08:00
一直觉得 numpy 是个比较神的库

竟然有
mat_a[...] = mat_b[:, 1, :, :] 这种操作。谁知道这种运算符是咋搞出来的?没时间查源码。
ToughGuy
2017-10-12 17:48:48 +08:00
这不就登录传一个 bool 值进去么, 有神码奇怪的。
ToughGuy
2017-10-12 17:50:06 +08:00
In [1]: x = lambda x: print(x)
In [2]: x(1>2)
False
In [3]: x(1>0)
True
ToughGuy
2017-10-12 17:52:30 +08:00
额 上面例子匿名函数变量名和参数一样, 看起来有点奇怪。

In [1]: x = lambda y: print(y)
In [2]: x(1>2)
False
In [3]: x(1>0)
True
In [4]: print(1>2)
False
In [5]: print(1>0)
True
xmcp
2017-10-12 18:08:04 +08:00
@ToughGuy 不好意思,这还真不是一个 bool 值,那行代码的作用是按照那两列的大小关系筛选数据库
linuxchild
2017-10-12 19:03:28 +08:00
重构了吧 - -
CSM
2017-10-12 19:26:57 +08:00
@northisland Python 里的 `...` 是 `ellipsis` 的实例,又名 `Ellipsis`:
>>> ...
Ellipsis
>>> ... is Ellipsis
True
>>> type(Ellipsis)
<class 'ellipsis'>

而 `mat_b[:, 1, :, :] ` 就是个多维切片嘛。。。
yonka
2017-10-12 21:31:21 +08:00
class Field:
def field_value(self, o):
return getattr(o, field_name) # field_name 用 meta class 等机制得到
def __gt__(self, other):
return lambda o: cmp(self.field_value(o), other.field_value(o))
weifding
2017-10-13 08:21:51 +08:00
就是个匿名函数。
msg7086
2017-10-13 08:33:49 +08:00
大致可以理解成 model.c.filed1.__gt__(model.c.cfiled2) 。
DSL 里比较常用的技巧,重载各种运算符然后返回各种构造器并且内部构建语法树。
ToughGuy
2017-10-13 15:42:03 +08:00
@xmcp

被表象迷惑了, 哈哈哈哈。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/397038

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX