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?

1
  • 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 Commented May 20, 2012 at 16:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.