将表达式传递给函数? [英] Passing expressions to functions?

查看:99
本文介绍了将表达式传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定我的意思,所以请忍受.

I'm not quite sure what I mean here, so please bear with me..

在SQLAlchemy中,似乎应该将表达式传递给

In SQLAlchemy, it appears I'm supposed to pass an expression to filter() in certain cases. When I try to implement something like this myself, I end up with:

>>> def someFunc(value):
...    print(value)

>>> someFunc(5 == 5)
True

如何从函数内部获取传递给==的值?

How do I get the values passed to == from inside the function?

我正在努力实现这样的目标

I'm trying to achieve something like this

 >>> def magic(left, op, right):
 ...    print(left+" "+op+" "+right)

 >>> magic(5 == 5)
 5 == 5

如果其中一个参数是对象怎么办?

What about if one of the parameters was an object?

推荐答案

如果将"op"设为函数,则可以实现示例:

You can achieve your example if you make "op" a function:

>>> def magic(left, op, right):
...     return op(left, right)
...
>>> magic(5, (lambda a, b: a == b), 5)
True
>>> magic(5, (lambda a, b: a == b), 4)
False

这比传递字符串更像Pythonic.像 sort() 之类的功能就是这样.

This is more Pythonic than passing a string. It's how functions like sort() work.

那些带有filter()的SQLAlchemy示例令人费解.我不了解有关SQLAlchemy的内部知识,但是我猜在像query.filter(User.name == 'ed')这样的示例中,正在发生的情况是User.name是特定于SQLAlchemy的类型,而对__eq()函数的奇怪实现会生成SQL filter()函数而不是进行比较.即:他们已经制作了特殊的类,使您可以键入发出SQL代码的Python表达式.这是一种不寻常的技术,除非构建一种将两种语言(例如ORM)架桥起来的方法,否则我将避免使用这种技术.

Those SQLAlchemy examples with filter() are puzzling. I don't know the internals about SQLAlchemy, but I'm guessing in an example like query.filter(User.name == 'ed') what's going on is that User.name is a SQLAlchemy-specific type, with an odd implementation of the __eq() function that generates SQL for the filter() function instead of doing a comparison. Ie: they've made special classes that let you type Python expressions that emit SQL code. It's an unusual technique, one I'd avoid unless building something that's bridging two languages like an ORM.

这篇关于将表达式传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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