Is there a Python equivalent to the C# ?. and ?? operators?

前端 未结 1 1841
盖世英雄少女心
盖世英雄少女心 2021-01-04 13:10

For instance, in C# (starting with v6) I can say:

mass = (vehicle?.Mass / 10) ?? 150;

to set mass to a tenth of the vehicle\'s mass if ther

相关标签:
1条回答
  • 2021-01-04 13:38

    No, Python does not (yet) have NULL-coalescing operators.

    There is a proposal (PEP 505 – None-aware operators) to add such operators, but no consensus exists wether or not these should be added to the language at all and if so, what form these would take.

    From the Implementation section:

    Given that the need for None -aware operators is questionable and the spelling of said operators is almost incendiary, the implementation details for CPython will be deferred unless and until we have a clearer idea that one (or more) of the proposed operators will be approved.

    Note that Python doesn't really have a concept of null. Python names and attributes always reference something, they are never a null reference. None is just another object in Python, and the community is reluctant to make that one object so special as to need its own operators.

    Until such time this gets implemented (if ever, and IronPython catches up to that Python release), you can use Python's conditional expression to achieve the same:

    mass = 150 if vehicle is None or vehicle.Mass is None else vehicle.Mass / 10
    
    0 讨论(0)
提交回复
热议问题