Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

oop

class

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?

like image 886
Lem0n Avatar asked May 13 '26 04:05

Lem0n


1 Answers

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.

like image 160
Fred Foo Avatar answered May 14 '26 18:05

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!