可以保存成变量一条件吗? [英] Can be saved into a variable one condition?

查看:31
本文介绍了可以保存成变量一条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将条件本身存储在变量中,而不是立即返回它,何时声明?

It would be possible to store the condition itself in the variable, rather than the immediate return it, when to declare it?

示例:

a = 3
b = 5

x = (a == b)
print(x)

a = 5
print(x)

回报是

False
False

然而,我希望得到

False
True

我只是在享受 Python 的魔力.我知道可以使用函数,但我想知道是否可以使用变量.

I'm just having fun with the magic of Python. I know it is possible using a function, but I wonder if it is possible using a variable.

推荐答案

条件总是立即求值.如果您想根据需要对其进行评估,可以将其设为函数或 lambda 表达式:

The condition is always evaluated immediately. If you want to evaluate it on demand, you could make it a function or a lambda expression:

x = lambda: a == b
print(x())

此外,您可能会使用一些黑魔法并创建一个在打印时评估条件的类:

Also, you could probably do some black magic and make a class that evaluates the condition when it's printed:

class Condition:
  def __init__ (self, cond):
    self.cond = cond
  def __str__ (self):
    return str(self.cond())

x = Condition(lambda: a == b)
print(x)

这仅用于教育目的,请勿在生产中使用它.另请注意,它仅适用于打印语句 - 要使其适用于 if 语句等,您还必须覆盖 __bool__ (python 3) 或 __nonzero__(python 2).

This is only for educational purposes though, don't use it in production. Also note that it onl works in print statements - to make it work in if statements etc you would also have to override __bool__ (python 3) or __nonzero__ (python 2).

这篇关于可以保存成变量一条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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