Salty
Salty

Reputation: 11

Python: Instantiate class B within a class A instantiation, <class A name> object has no attribute <class B attribute>

Python: I'm using the requests module to work with an API and I'm looking at using classes. I'm getting an attribute error:

apic.py module: (class 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)

script:

import requests
import apic

sesh = apic.Ses()

print(sesh.login())

If I remove the call to login() from apic:

sesh = apic.Ses()

I can see it prints self.headers (sesh.headers) just fine:

So it seems my syntax is the script is the issue.

.Session is a class in requests (class B)

.post and .headers are functions in the Session class.

My questions:

If I'm instantiating class B in class A instantiation, how should I be calling attributes of class B.

Should I just not be attempting this? (I'm looking at using classes in this way to clean up my script, it's not something I necessarily need to do.)

Upvotes: 1

Views: 104

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599798

You can't just assign to self. That's just a local variable within the __init__ method.

I don't know why you want to do that anyway. Instead you should be defining the session as an attribute of the instance:

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} ) 
    ...

Upvotes: 1

Related Questions