我全局初始化了一个变量,然后当我去更改变量时,它的类型从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']
谢谢大家
对
api_data
内部的getApiData
所做的分配在其他任何地方都不可见,因为您没有将其标记为全局将
global api_data
添加到getApiData
的开头顺便说一句,如果您想赋值给一个全局变量,您只需要global语句—您可以在不使用该语句的情况下很好地访问它们的值。所以严格来说你不需要
global apiEndpoint
相关问题 更多 >
编程相关推荐