【发布时间】:2022-11-25 02:07:50
【问题描述】:
我有一个方法,如果所有 3 个语句都为真,我希望它返回真。如果其中任何一个为假,该方法应返回假。
def check_valid(self, a, b):
statement1 = self.x == 0
statement2 = self.y == a
statment3 = self.z = b
return statement1 ^ statement2 ^ statement3
我正在使用 xor 来验证所有语句是否具有相同的值,但如果所有语句都为假,则该方法将返回 true,这不是预期的行为。
为了解决这个问题,我正在考虑像这样向 return 语句添加一个 true :
return true ^ statement1 ^ statement2 ^ statement3
但我认为这不是最好的方法。 有没有更清洁/更好的方法来做到这一点?
【问题讨论】:
-
你是想写
statement3 = self.z == b吗? -
我想你要找的是
return all([statement1, statement2, statement3]) -
你也可以使用
statement1 and statement2 and statement3
标签: python boolean boolean-logic xor boolean-operations