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?
The C function always has two arguments, conventionally named self and args. The self argument points to the module object for module-level functions; for a method it would point to the object instance. The args argument will be a pointer to a Python tuple object containing the arguments.
The python default implementation is written in C programming and it's called CPython. So it's not very uncommon to use C functions in a python program. In this tutorial, we learned how to easily call C functions in a python program.
Python is written in C (actually the default implementation is called CPython).
Interpreted languages like Python, Ruby, and PHP have their primary implementations written in C. It is even used by compilers for other languages to communicate with the machine.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With