3

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?

Lem0n
  • 1,217
  • 1
  • 14
  • 22
  • I would pass the connection in as a parameter to each classes' `__init__()`. Or, if you don't plan on only using this connection throughout the program, you can inherit all of you classes from `MyDB` – Joel Cornett May 20 '12 at 16:01

1 Answers1

3

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836