jb.*_*jb. 6 python conditional-operator
我看到这个问题,但它使用?? 运算符作为空检查,我想将它用作bool true/false测试.
我在Python中有这个代码:
if self.trait == self.spouse.trait:
trait = self.trait
else:
trait = defualtTrait
Run Code Online (Sandbox Code Playgroud)
在C#中我可以这样写:
trait = this.trait == this.spouse.trait ? this.trait : defualtTrait;
Run Code Online (Sandbox Code Playgroud)
在Python中有类似的方法吗?
Gre*_*ill 11
是的,你可以写:
trait = self.trait if self.trait == self.spouse.trait else defaultTrait
Run Code Online (Sandbox Code Playgroud)
这在Python中称为条件表达式.