为什么变量在某些类中共享而在其他类中不共享?

时间:2013-12-25 11:02:15

标签: python

我有一个问题,我的Classes继续创建新的数据库连接,而我正在试图理解我做错了什么...这是我的结构:

index.py
 |_ a/const.py    ( not a Class, just several functions )
      db = None

      def get_connection():
         global db

         if not db:    
           db = created_new_connection()
           print "New connection has been created"
         else:
           print "Connection already exists"

         return db

 |_ a/group.py   ( import const, Class )
 |_ a/user.py    ( import const, Class )

“index.py”导入“const”和另一个后来使用“group”和“user”的模块

当我运行index.py时,我得到:

group.py "New connection has been created"
user.py "New connection has been created"

因此,对于测试,我尝试在“index.py”中创建连接,但现在我得到了:

index.py "New connection has been created"
group.py run func1() "Connection already exists"
group.py run func2() "Connection already exists"
user.py "New connection has been created"

现在 - 我很困惑。 “组”和“用户”的写法几乎完全相同。如果“group”运行“get_connection()”它按预期工作(已经存在),之后当“user”运行“get_connection()”时它会创建一个新连接....

有趣的是(对我来说)当我在相同目录中创建文件(a,b,c,d)(以保持结构)并在所有文件中导入“c.py”时,“a”创建了连接,但“b和d”没有创建新连接,他们使用了仍然打开的连接....(这是我所期待的)

有什么想法吗?提前谢谢......

2 个答案:

答案 0 :(得分:1)

尝试将其更改为:

def get_connection():
    global db

    if not db:    
        db = created_new_connection()
        print "New connection has been created"
    else:
        print "Connection already exists"

    return db

如果你有这个,那么函数第二次进入第一个块的唯一可能性是created_new_connection()函数返回一个评估为False的东西(例如None或者空str或空list,...)。

或者,您可能会遇到Python加载模块两次的情况,如here所述:基本上如果您使用不同的相对路径导入模块,Python会将它们视为不同的模块,并加载它们两次。此博客文章中建议的解决方案是始终使用其顶级路径加载模块。

答案 1 :(得分:0)

您也可以考虑使用“Borg”类,而不是使用全局变量。这是单例类的Python替代。

<强> database.py

class Database:

    __shared_state = {}
    db = None

    def __init__(self):
        self.__dict__ = self.__shared_state

    def get_connection(self):

        if not self.db:
            self.db = self.create_new_connection()
            print "New connection has been created"
        else:
            print "Connection already exists"

        return self.db

    def create_new_connection(self):
        # create and return new connection

然后像from database import Database一样导入此类,并获得与Database().get_connection()的连接。

相关问题