python 函数说“函数中没有属性”

python function says " no attribute in function"

我运行在程序下面获取一些值,以便我稍后在主程序中全局使用这些值

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:通过以下解决

    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)

在您的函数中,您将 tenant_id 设置为函数对象的属性 get_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)

或者更好的方法:如评论中所建议,return tenant_id 作为元组的一部分在函数的 return 值中。

使用全局变量减速解决

    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)