开发者

Python shorthand conditional

Here's a quick one...

In Python one can do:

foo = foo1 if bar1 else foo2

And that's cool, but how can I just get a True or False without having to write

foo = True if bar1 else False

For exa开发者_Python百科mple, in JS you can forcibly cast a boolean type by doing

var foo = !!bar1;


Call bool on the object:

bool(bar1)


Similar to JavaScript, you can use logical negation in Python. This uses the keyword not. One disadvantage of bool is you can change its value, as this is not a reserved word. If bool variable's value is not callable. For example, bool = 7, an error will be raised. If bool variable's value is callable. For example, bool = int, you may get an unexpected value.

JavaScript

!!bar1

Python

not not bar1
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜