Python:在类A实例化中实例化类B,<class a =“”name =“”>对象没有属性<class b =“”attribute =“”>

时间:2016-09-27 15:43:29

标签: python class attributes instantiation

的Python: 我正在使用请求模块来处理API,我正在使用类。我收到属性错误:

apic.py模块:(A类)

import requests
import json

class Ses:

    def __init__(self):
        self = requests.Session() 
        self.headers = {'Content-Type': 'application/json'}
        print(self.headers)

    def login(self, cname, uname, pword):
        res = self.post( 'https://api.dynect.net/REST/Session/', params = {'customer_name': cname, 'user_name': uname, 'password': pword} ) 
        self.headers.update({'Auth-Token': json.loads(res.text)['data']['token']})
        print( json.loads(res.text)['msgs'][0]['INFO'], '\n' )
        return json.loads(res.text)

脚本:

import requests
import apic

sesh = apic.Ses()

print(sesh.login())
  • AttributeError:'Ses'对象没有属性'post'

如果我从apic中删除对login()的调用:

sesh = apic.Ses()

我可以看到打印self.headers(sesh.headers)就好了:

  • {'Content-Type':'application / json'}

所以我的语法似乎是脚本是问题。

.Session是请求中的一个类(B类)

.post和.headers是Session类中的函数。

我的问题:

如果我在A类实例化中实例化B类,我应该如何调用B类的属性。

我应该不尝试这个吗? (我正在以这种方式使用类来清理我的脚本,这不是我必须要做的事情。)

1 个答案:

答案 0 :(得分:1)

您不能只分配给self。这只是__init__方法中的局部变量。

我不知道你为什么要那样做。相反,您应该将会话定义为实例的属性:

def __init__(self):
    self.session = requests.Session() 
    self.session.headers = {'Content-Type': 'application/json'}
    print(self.session.headers)

def login(self, cname, uname, pword):
    res = self.session.post('https://api.dynect.net/REST/Session/', params = {'customer_name': cname, 'user_name': uname, 'password': pword} ) 
    ...