Python 变量赋值 没有成功,偶发性现象 诡异

2020-04-21 16:32:01 +08:00
 smallgoogle

原始代码:

def get_http_ip():
    res = requests.get('http://www.xxx.com')
    res = json.loads(res.text)
    if res['code'] == 200:
        print(res['data'])    # 这里打印结果都还是正常的
        time.sleep(5)    # 我猜有可能有人说太快了,那么我这里给一个定时器。
        # 我猜,肯定有人说你在这写一个变量先赋值一下,然后再把变量返回出去
        # 我当然试过了,结果依然是一样的,一样会出现 None
        return res['data']
    else:
        time.sleep(1)
        get_http_ip()


def start():
    info = get_http_ip()
    print(info)    # 这个位置有些时候会打印出 None,这是为啥呢?


if __name__ == '__main__':
    start()



修正的代码:

ip_list = ''

def get_http_ip():
    global ip_list
    res = requests.get('http://www.xxx.com')
    res = json.loads(res.text)
    if res['code'] == 200:
        ip_list = res['data']    # 我把结果赋值给全局变量
        return res['data']
    else:
        time.sleep(1)
        get_http_ip()


def start():
    global ip_list
    info = get_http_ip()
    if info == None:    # 我这里写一个判断如果返回 None 我就用全局变量赋值
        info = ip_list
    print(info)


if __name__ == '__main__':
    start()



那么问题来了,为啥我第一个办法有些时候会返回 None 呢?
我瞎猜,是不是内存指针跟不上?
就是前辈们指教一下,什么原因导致的?

1237 次点击
所在节点    Python
5 条回复
jyyx
2020-04-21 16:34:50 +08:00
递归那里没有返回, else 里面没有 return
改成 return get_http_ip()
Virace
2020-04-21 16:38:24 +08:00
马虎
wzwwzw
2020-04-21 16:39:46 +08:00
递归哪里修改成 return get_http_ip()
smallgoogle
2020-04-21 16:41:38 +08:00
@jyyx @Virace @wzwwzw 沉了 沉了。对不起。对不起。占用资源了。哎。。。
littleylv
2020-04-21 16:42:38 +08:00
递归,了解一下递归
答案楼上已经说了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/664696

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX