python函数表示“函数中没有属性”
我在下面运行proecedure来获取一些值,以便稍后在主程序中全局使用这些值python函数表示“函数中没有属性”,python,function,attributes,Python,Function,Attributes,我在下面运行proecedure来获取一些值,以便稍后在主程序中全局使用这些值 import requests import json import sys client= 'test' def get_path(client): headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()} URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+c
import requests
import json
import sys
client= 'test'
def get_path(client):
headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()}
URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+client
response=requests.get(URL,headers=headers)
jout = json.loads(response.text)
azure_path=jout['data']['account_id']
get_path.tenant_id=jout['data']['tenant_id']
return azure_path
tenant = ('tenant is :' + get_path(client).tenant_id)
print(tenant)
但是说没有属性是错误的
tenant = ('tanant is :' + get_path.tenant_id(client))
AttributeError: 'function' object has no attribute 'tenant_id'
我确信当我打印名为jout的变量时,它是有值的,它确实有租户id
编辑1:通过以下方式解决它
在函数中,将租户id设置为函数对象get\u path的属性。。。这是一种相当奇怪的编码方式 要使此工作正常,您可以修改以下代码段:
def get_path(arg):
get_path.tenant_id = '123' + arg
return 'something else'
# get the function object
myfunction = get_path
# call the function
myfunction('myargument')
# consume the function object attribute
tenant = ('tenant is :' + myfunction.tenant_id)
或者更好的方法:按照注释中的建议,在函数的返回值中作为元组的一部分返回租户id。通过使用全局变量来解决它
import requests
import json
import sys
client= 'test'
tenant_var = None
def get_path(client):
global tenant_var
headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()}
URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+client
response=requests.get(URL,headers=headers)
jout = json.loads(response.text)
azure_path=jout['data']['account_id']
tenant_var=jout['data']['tenant_id']
return azure_path
tenant = ('tenant is :' + tenant_var)
print(tenant)
get_path.tenant_idI建议:azure_path=jout['data']['account_id']tenant_id=jout['data']['tenant_id']返回azure_path,tenant_id=get_pathclient tenant='tenant is:'+tenant_id',直到出现相同错误。Huhs通过将租户id声明为全局变量来解决此问题。。然后在def内部提到,我将使用该变量并逐个返回,而不是作为tuple,因为我是在url上形成的,所以tuple没有帮助..谢谢你的建议
import requests
import json
import sys
client= 'test'
tenant_var = None
def get_path(client):
global tenant_var
headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()}
URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+client
response=requests.get(URL,headers=headers)
jout = json.loads(response.text)
azure_path=jout['data']['account_id']
tenant_var=jout['data']['tenant_id']
return azure_path
tenant = ('tenant is :' + tenant_var)
print(tenant)