变量类型从全局变量更改为方法变量为什么?

variable type change from global variable to method variable why?

我全局初始化一个变量,然后当我去更改变量时,它的类型从字典(好)变为字符串(坏),我有点确定为什么但不是真的。我不是 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']

谢谢大家

getApiData 中对 api_data 进行的分配将不会在其他任何地方可见,因为您没有将其标记为全局。

global api_data 添加到 getApiData 的开头。

顺便说一句,如果你想分配给一个全局变量,你只需要全局语句——你可以在没有语句的情况下访问它们的值。所以严格来说你不需要 global apiEndpoint.