【问题标题】:Store comparison in variable (or execute comparison when it's given as an string)将比较存储在变量中(或在以字符串形式给出时执行比较)
【发布时间】:2011-01-16 01:35:40
【问题描述】:

我想知道超级强大的 python 是否允许将比较存储在变量中,或者,如果不允许,是否可以在作为字符串(“==”或“!= ")

我想让我的程序的用户有机会在字符串中进行比较。

例如,假设我有一个...“产品”列表,而用户想要选择制造商为“foo”的产品。他可以输入如下内容: Product.manufacturer == "foo" 如果用户想要制造商不是“bar”的产品,他会输入 Product.manufacturer != “bar”

如果用户将该行输入为字符串,我会创建一个结构如下的树:

            !=
         /     \
manufacturer   bar

我想让该比较正常运行,但如果 != 是一个字符串,我不知道如何实现。

“制造商”字段是一个属性,因此我可以从 Product 类中正确获取它并将其(作为属性)存储在叶子中,并且......“bar”是只是一个字符串。我想知道我是否可以做类似于我对“制造商”所做的事情:用“可调用”(某种)东西存储它:带有比较器的属性:!=

我尝试过使用“eval”,它可能会起作用,但比较实际上将用于查询 MySQL 数据库(使用 sqlalchemy),我有点担心它的安全性......

我们将不胜感激任何想法。谢谢!

PS: 所有这一切的想法是能够生成一个 sqlalchemy 查询,所以如果用户输入字符串: Product.manufacturer != "foo" || Product.manufacturer != "bar"

...我的树可以生成以下内容: sqlalchemy.or_(Product.manufacturer !="foo", Product.manufacturer !="bar")

由于 sqlalchemy.or_ 是可调用的,我也可以将它存储在其中一个叶子中...我只看到“!=”有问题

【问题讨论】:

    标签: python sqlalchemy call


    【解决方案1】:

    我没有太多使用 SQLAlchemy,但我猜它使用Python's operator overloading 来处理这些比较。如果这是真的,那么您可以使用属性的魔术方法。例如:

    Product.manufacturer == 'bar' => Product.manufacturer.__eq__('bar')
    Product.manufacturer != 'foo' => Product.manufacturer.__ne__('foo')
    

    您应该能够在属性对象上为适当的魔术方法执行getattr

    method_map = {'==': '__eq__', '!=': '__ne__'}
    comparison = getattr(Product.manufacturer, method_map[op])   # Here, 'op' is the operator (!=)
    sqlalchemy.or_(comparison('foo'), comparison('bar'))         # Equivalent to: Product.manufacturer != 'foo' || Product.manufacturer != 'bar'
    

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多