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

你离开我真会死。 提交于 2019-12-22 05:13:49

问题


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.spouse.trait ? this.trait : defualtTrait;

Is there a similar way to do this in Python?


回答1:


Yes, you can write:

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

This is called a Conditional Expression in Python.




回答2:


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;


来源:https://stackoverflow.com/questions/7692121/python-version-of-cs-conditional-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!