开发者

What is the equivalent code to the sentence in Python below?

开发者 https://www.devze.com 2023-03-26 21:28 出处:网络
post_data = None if post_args is None else urllib.u开发者_如何学JAVArlencode(post_args) I can\'t understand what this code really do. Any help?
post_data = None if post_args is None else urllib.u开发者_如何学JAVArlencode(post_args)

I can't understand what this code really do. Any help?

Thanks.


post_data = None if post_args is None else urllib.urlencode(post_args)

is equivalent to the following:

if post_args is None:
    post_data = None 
else: 
    post_data = urllib.urlencode(post_args)


That's a conditional expression, introduced in python 2.5. (It really ought to be on one line).

It does exactly what it reads like -- post_data is None if post_args is None, otherwise it's assigned the result of urllib.urlencode(post_args).

A more verbose way of writing it would be

if post_args is None:
    post_data = None
else:
    post_data = urllib.urlencode(post_args)

or, using the and-or trick:

post_data = (post_args is None and [None] or [urllib.urlencode(post_args)])[0]
0

精彩评论

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