1

I have one class, which is reading data from a JSON file:

import os   
import json
from db_connection import DB_Connection

class RA_Admin:

    def __init__(self):
        data = None
        self.load_access_data()

    def load_access_data(self):
        with open('../docs/db_data.json') as data_file:
            self.data = json.load(data_file)

a = RA_Admin()
db_con = DB_Connection(a.data)
db_con.read_data()

I wrote a second class to connect to a database:

import mysql.connector

class DB_Connection:

    def __init__(self, data):
        database_connection = None
        cursor = None
        user = data["database"]["user"]
        paw = data["database"]["paw"]
        ip_address = data["database"]["ip_adress"]
        db_name = data["database"]["database_name"]
        port = data["database"]["port"]

    def read_data(self):
        database_connection = mysql.connector.connect(user = self.user, password = self.paw, host=self.ip_address, port=self.port, database=self.db_name)
        self.cursor = database_connection.cursor(dictionary=True)

I get the following error:

database_connection = mysql.connector.connect(user = self.user, password = self.paw, host=self.ip_address, port=self.port, database=self.db_name)
AttributeError: DB_Connection instance has no attribute 'user'

I can print the user in the __init__ method and the other attributes, but why are they not used in read_data?

1 Answer 1

4

You need self:

 self.user = data["database"]["user"]
 self.paw = data["database"]["paw"]
 ....

what-is-the-purpose-of-self-in-python

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.