在python中使用对象的属性

时间:2015-04-27 10:48:45

标签: python oop

我有一个类,它从JSON文件中读取数据:

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()

我写了第二个类来连接数据库:

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)

我收到以下错误:

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'

我可以使用__init__方法和其他属性打印用户,但为什么不在read_data中使用它们?

1 个答案:

答案 0 :(得分:4)

你需要自己:

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

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