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?

Kevin J. Chase
  • 3,856
  • 4
  • 21
  • 43
ThoFin
  • 1,467
  • 14
  • 20

1 Answers1

4

You need self:

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

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

Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321