简体   繁体   中英

Using attributes of an object in python

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 ?

You need self:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM