变量类型从全局变量变为方法变量的原因是什么?

2024-10-02 00:20:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我全局初始化了一个变量,然后当我去更改变量时,它的类型从dictionary(good)变为string(bad),我有点确定原因,但不是真的。我不是100%的python范围

下面是完整的代码,请注意,我有很多打印语句,我是作为测试使用。我包括所有的代码到问题的关键点,给大家一个完整的掌握我正在努力做什么

totalEntries = 0
print 'this is first ' + str((type(totalEntries))) #prints type int (good)
perPage = 0
currentPage = 1
Pcity = ''

api_data = ''
is_last_page = False
apiCallNum = 1
tableDefined = False


def getApiData(city):
    global Pcity
    global apiCallNum
    global apiEndpoint
    Pcity = city
    apiEndpoint = #just a link ignore this

    api_data = requests.get(apiEndpoint).json()
    print(api_data)
    print('your testing this' + str(type(api_data))) #prints dict (good)

    print ("Current API Call " + str(apiCallNum))

    apiCallNum += 1



    print('your testing this' + str(type(api_data))) #prints dict (good)


def populateVars():
    global totalEntries

    print "this is second " + str(type(totalEntries)) #prints int (good)

    print('your testing this' + str(type(api_data))) #prints string (bad)
    totalEntries = api_data['total_entries']

谢谢大家


Tags: apiyourdataistypethisprintsglobal
1条回答
网友
1楼 · 发布于 2024-10-02 00:20:38

api_data内部的getApiData所做的分配在其他任何地方都不可见,因为您没有将其标记为全局

global api_data添加到getApiData的开头

顺便说一句,如果您想赋值给一个全局变量,您只需要global语句—您可以在不使用该语句的情况下很好地访问它们的值。所以严格来说你不需要global apiEndpoint

相关问题 更多 >

    热门问题