Creating a Python class for "just one instance"?

oop, python

Solution

A module is meant to enclose common structures in a "namespace". But really in python a module is just a file and you can organize them however you want. Some people put a lot of functionality in one module. Some people spread them out over packages or sub-packages. Depends on the reusability you want. If a module has a ton of dependencies and you will want to reuse just a small amount, it makes sense to split them.

A class allows you to define types that can be inherited as sub-types. They also let you define a state with each instance of that class.

When your class has no state, and only staticmethods/classmethods, chances are you don't need a class. You just need functions.

Also, you can't create a module and use it like a class. A module can't have subclasses. They just have a basic module init once on load and then a scope of objects.

If what you are after are constants, meaning they are defined once for the life of the app, then just create a constants.py module with a bunch of primitive types like strings, dicts, and lists.

Problem

I'm asking this question with regards to Python, though it's probably applicable to most OOP languages. When I only expect to use the data model only once in any program, I could either make a class with class/static methods and attributes or just make a regular class and instantiate it once and only use that one copy. In this case, which method is better and why? With python, I could also write a module and use it like I would a class. In this case, which way is better and why? Example: I want to have a central data structure to access/save data to files. Module way: data.py ``` attributes = something ... def save(): ... ``` main.py ``` import data data.x = something ... data.save() ``` Class way: ``` class Data: attributes = something @classmethod def save(cls): Data.x = something Data.save() ``` instance way ``` class Data: def save(self): data = Data() data.x = something data.save() ```

Original source

Related problems