开发者

Python version of C#'s conditional operator (?)

I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test.

I have this code in Python:

if self.trait == self.spouse.trait:
    trait = self.trait
else:
    trait = defualtTrait

In C# I could write this as:

trait = this.trait == this开发者_如何学C.spouse.trait ? this.trait : defualtTrait;

Is there a similar way to do this in Python?


Yes, you can write:

trait = self.trait if self.trait == self.spouse.trait else defaultTrait

This is called a Conditional Expression in Python.


On the null-coalescing operator in C#, what you have in the question isn't a correct usage. That would fail at compile time.

In C#, the correct way to write what you're attempting would be this:

trait = this.trait == this.spouse.trait ? self.trait : defaultTrait

Null coalesce in C# returns the first value that isn't null in a chain of values (or null if there are no non-null values). For example, what you'd write in C# to return the first non-null trait or a default trait if all the others were null is actually this:

trait = this.spouse.trait ?? self.trait ?? defaultTrait;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜