我看到了this question但它使用 ??运算符作为空检查,我想将其用作 bool true/false 测试。
我在 Python 中有这段代码:
if self.trait == self.spouse.trait:
trait = self.trait
else:
trait = defualtTrait
在 C# 中我可以这样写:
trait = this.trait == this.spouse.trait ? this.trait : defualtTrait;
在 Python 中有类似的方法吗?
最佳答案
是的,你可以这样写:
trait = self.trait if self.trait == self.spouse.trait else defaultTrait
这叫做 Conditional Expression在 Python 中。
关于C# 的条件运算符 (?) 的 Python 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7692121/