首页 > 解决方案 > 在另一个脚本中使用类中的变量

问题描述

基本上,我需要在脚本中存储一些变量并在另一个脚本中使用它们:

存储变量.py
class Setup():
    def setup():
        a = 'X'

        if a == 'X':
            #Credentials for X
            database = 'a'
            user = 'b'
            password = 'c'
            host = 'd'
            port = 4
        
        elif a == 'Y':
            #Credentials for Y
            database = 'x'
            user = 'y'
            password = 'z'
            host = 'w'
            port = 7

然后在我的第二个脚本中使用基于“if”语句的特定变量,如下所示:

连接.py
class Connection:
    def __init__(self, host, database, port, user, password):   
        self.conn = psycopg2.connect(
            database=database,
            user=user,
            password=password,
            host=host,
            port=port
        )

标签: python

解决方案


您需要为第一个类(设置)创建一个实例,然后使用变量。

s = setup()
c = connection (s.host,s.username...)

推荐阅读