Create an attribute of a class in Python that uses class method of the instance to call on self.attribute. AttributeError:type object has no attribute

Question:

I am a beginner in Python but I have programmed a little before and have taken some classes in Java.

I am trying to understand how to use classes in python. I’m working with the spotify api to get an artist’s information from the api. I created a class where I define init and a @classmethod get_spapi, or get the spotify api object.

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials #to access spotify database

client_id = 'x'
client_secret = 'xx'

class spapi:

    def __init__(self, client_id = 'x', client_secret = 'xx'):
        self.client_id = client_id
        self.client_secret = client_secret

        self.client_credentials_manager = SpotifyClientCredentials(client_id = self.client_id,
        client_secret = client_secret)
#        print('verifying credentials: {}'.format(self.client_credentials_manager))

    @classmethod
    def get_spapi(self):
        credentials = self.client_credentials_manager
        return spotipy.Spotify(client_credentials_manager = credentials)

spotify_api = spapi(client_id, client_secret)

result = spotify_api.get_spapi()

I get the error AttributeError: type object ‘spapi’ has no attribute ‘client_credentials_manager’ at line 21 credentials = self.client_credentials_manager

I have been trying to understand why I cannot call on self.client_credentials_manager in the get_spapi class method. By putting self.client_credentials_manager in def __init__(), does it not become an attribute of the instance of the class, spotify_api

==========================================================

I understand that I can avoid most of this by running this as a simple script. But I am trying to get familiar with classes in python and this one I can’t figure out how to make it work with a similar structure.

Asked By: chineseninja

||

Answers:

The reason why you get the error

AttributeError: type object 'spapi' has no attribute 'client_credentials_manager'

is because you’re marking get_spapi as a class method (i.e. bound to the class), and not as a member method (i.e. bound to the specific instance of the class).

The error will go away after you remove @classmethod.

Answered By: JustLearning