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". I don't wanna make a new connection to the DB everytime a different class wants to do something.
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
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.
Often, when you'd use a singleton in other programming languages, you can get by in Python with a module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With