简体   繁体   English

如何在python中的不同类上使用相同的对象?

[英]how to use the same object on different classes in python?

This is probably a very basic question. 这可能是一个非常基本的问题。

I have some objects that I want to be created once and then used by many classes of my application, for instance "logging" and "db". 我有一些对象,我想创建一次,然后由我的应用程序的许多类使用,例如“logging”和“db”。 I don't wanna make a new connection to the DB everytime a different class wants to do something. 每当另一个班级想要做某事时,我不想与DB建立新的连接。

So my idea was to create a Class like: 所以我的想法是创建一个类,如:

class MyDB(object):
    mydb=createMySQLconnection()

then I'd do "from ... import MyDB" and use MyDB.mydb 然后我会“从...导入MyDB”并使用MyDB.mydb

would it work? 会有用吗? is this the best way to do that? 这是最好的方法吗?

This would work, but there's no reason to create a class. 这可行,但没有理由创建一个类。 Just put mydb in a module as a free-standing variable. 只需将mydb作为独立变量放入模块中。

Often, when you'd use a singleton in other programming languages, you can get by in Python with a module. 通常,当您在其他编程语言中使用单例时,您可以使用模块在Python中使用。

Here is an example for implementing singleton pattern in python. 这是在python中实现singleton模式的示例。

Python and the Singleton Pattern Python和Singleton模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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