Can Be Saved Into A Variable One Condition?
It would be possible to store the condition itself in the variable, rather than the immediate return it, when to declare it? Example: a = 3 b = 5 x = (a == b) print(x) a = 5 prin
Solution 1:
You can get this kind of reactive pattern by using a property:
classTest:def__init__(self, a, b):
self.a = a
self.b = b
@propertydefx(self):
returnself.a == self.b
Then:
>>>t = Test(a=3, b=5)>>>t.x
False
>>>t.a = 5>>>t.x
True
Solution 2:
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:
classCondition:
def__init__ (self, cond):
self.cond = cond
def__str__ (self):
returnstr(self.cond())
x = Condition(lambda: a == b)
print(x)
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).
Solution 3:
Sure, that's called a function! :)
defx(a, b):
return a == b
Solution 4:
No. You need a function for that.
def test(param_1, param_2):
return param_1 == param_2
a = 3
b = 5
print(test(a, b))
a = 3
print(test(a, b))
Solution 5:
If you only want the magic to happen when you print x, override __str__
.
>>>classX(object):...def__str__(self):...returnstr(a == b)...>>>x = X()>>>print(x)
False
>>>a = 5>>>print(x)
True
Post a Comment for "Can Be Saved Into A Variable One Condition?"