Python: Instantiate class B within a class A instantiation, <class A name> object has no attribute <class B attribute>
<p>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:</p>

<p><strong>apic.py module:</strong> (class A)</p>

<pre><code>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)
</code></pre>

<hr>

<p><strong>script:</strong></p>

<pre><code>import requests
import apic

sesh = apic.Ses()

print(sesh.login())
</code></pre>

<ul>
<li>AttributeError: 'Ses' object has no attribute 'post'

<hr></li>
</ul>

<p>If I remove the call to login() from apic:</p>

<pre><code>sesh = apic.Ses()
</code></pre>

<p>I can see it prints self.headers (sesh.headers) just fine: </p>

<ul>
<li>{'Content-Type': 'application/json'}</li>
</ul>

<p>So it seems my syntax is the script is the issue.</p>

<p>.Session is a class in requests (class B)</p>

<p>.post and .headers are functions in the Session class.</p>

<p>My questions:</p>

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

<p>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.)</p>

<p>You can't just assign to <code>self</code>. That's just a local variable within the <code>__init__</code> method. </p>

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

<pre><code>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} ) 
    ...
</code></pre>

python class attributes instantiation