0

Suppose there are several presses, each one published many books I am going to handle many records like 'press name, book name'

I want create the class 'Press' by a unique name(string), but only different string can produce different instances of class 'Press'.

so, I need a class work like 'factory', create a new instance when a record contains a new press, but it also work as singleton if there are already exists which has the same names.

2
  • Singletons aren't really a thing in python. For your task, you can simply create a dictionary with the unique names as keys and Press objects as values. Commented Sep 20, 2020 at 8:58
  • yes, a global dict can solve this but ugly Commented Sep 20, 2020 at 13:07

1 Answer 1

1

You could create a dict with the unique names as keys and Press objects as values. This doesn't need to be a global dict. You can wrap it in some class like that:

class Press:
    def __init__(self, name):
        self.name = name
        self.books = []

class PressManager:
    presses = {}

    @classmethod
    def get_press(cls, name):
        if name not in cls.presses:
            cls.presses[name] = Press(name)
        return cls.presses[name]


example_press = PressManager.get_press("Test")

I implemented get_press() as a class method, because I think this is what you had in mind.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.