Creating a Python class for "just one instance"?

I ask this question regarding Python, although it is probably applicable to most OOP languages.

When I only expect to use the data model only once in any program, I can either make the class using class / static methods and attributes, or just create a regular class and instantiate one instance and use only one copy. In this case, which method is better and why?

With python, I could also write a module and use it as a class class. In this case, which way is better and why?

Example: I want to have a central data structure for accessing / saving data to files.

Module Way:

data.py

attributes = something
...
def save():
...

main.py

import data
data.x = something
...
data.save()

Grade:

class Data:
    attributes = something
    @classmethod
    def save(cls):

Data.x = something
Data.save()

instance method

class Data:
    def save(self):

data = Data()
data.x = something
data.save()
+5
source share
2 answers

" ". python - , , . . . . , , .

, . .

staticmethods/classmethods, , . .

, . . init , .

, , .py , , dicts .

+5

, .

, random.random(), Random, . ,

my_random = random.Random()
my_random.seed('not needed but illustrative seed call')
coin_toss = my_random.random()

, . , random.py, ; , .

, Pythonic : , , .

+2

All Articles