Python从多个类读取数据并链接到主类对象的最佳方法

时间:2018-11-14 16:08:31

标签: python

导入cx_Oracle 从cx_Oracle导入DatabaseError

类DBconnection:     def init (自身,凭据):         self.connectionString =''         self.credentials =凭证         self.msg =''

def __repr__(self):
    return "<DBConnection: {} on '{}'>".format(self.msg, self.credentials)

def connect_db(self):
    try:
        self.connectionString = cx_Oracle.connect(self.credentials)
    except DatabaseError:
        self.msg = "Error TNS: no listener"
    else:
        self.msg = "Connection Successful"

1 个答案:

答案 0 :(得分:0)

您要的内容称为合成。只是谷歌“ Python组成”,你会发现很多例子和最佳实践。有许多不同的方法可以完成。我在这里给您两个小例子:

您可以通过对依赖关系进行硬编码来构成类之间的依赖关系,如下所示:

# example classes
import cx_Oracle

class DBConnector():
    def __init__(self, credentials):
        self.credentials = credentials

    def connect(self):
        return cx_Oracle.connect(self.credentials)

class DataReader():
    def __init__(self, credentials):
        self.connector = DBConnector(credentials)

# run example
credentials = {
    "server": "my_server",
    "port": 123,
    "database": "my_db"
}

my_reader = DataReader(credentials)
connection = my_reader.connector.connect()

但是,您也可以注入依赖项。如果您想了解为什么它很酷,这就是所谓的“依赖注入”,但是从本质上讲,它可以归结为您可以创建许多不同的DBConnector类,并且DataReader将能够使用它们的事实(例如,您可以创建一个第二类(连接到MySQL而不是oracle的DBConnectorMySQL)。您可以按照以下步骤进行操作:

# example classes
class DBConnector():
    def __init__(self, credentials):
        self.credentials = credentials

    def connect(self):
        return cx_Oracle.connect(self.credentials)


class DataReader():
    def __init__(self, connector):
        self.connector = connector

# run example
credentials = {
    "server": "my_server",
    "port": 123,
    "database": "my_db"
}

connector = DBConnector(credentials)
my_reader = DataReader(connector)
connection = my_reader.connector.connect()