0

I trying to preserve the first apparition of an object no matter how many times has been created before.

When I create an object of the class Capital and give it a name, I would like to extract the same name for all the next times I call the method.

I have the current code

class Capital:
    def __init__(self, city_name):
        self.name=city_name
    
    def name(self):
        return self.name

I would like to declare Mutiple objects of the same class

capital_1 = Capital("London")
capital_2 = Capital("Madrid")
capital_3 = Capital("Paris")

And all of them should return the first apparition

capital_2.name() == "London"
capital_3.name() == "London"

I have read of something called singletons, but I haven't found nothing but the same code that doesn't work for me

The next code I found raises an exception, but I don't want to raise anything

class Singletone(object):
    __initialized = False
    def __init__(self):
        if Singletone.__initialized:
            raise Exception("You can't create more than 1 instance of Singletone")
        Singletone.__initialized = True
DDela
  • 23
  • 7

0 Answers0