python-checkio/Blizzard/capital-city.py
2019-12-23 17:19:33 +01:00

45 lines
1.2 KiB
Python

class Capital:
class __Singleton:
def __init__(self, city_name):
self.val = None
self.city_name = city_name
def __str__(self):
return repr(self) + self.val
def name(self):
return self.city_name
instance = None
def __new__(cls, city_name): # _new_ est toujours une méthode de classe
if not Capital.instance:
Capital.instance = Capital.__Singleton(city_name)
return Capital.instance
def __getattr__(self, attr):
return getattr(self.instance, attr)
def __setattr__(self, attr, val):
return setattr(self.instance, attr, val)
@staticmethod
def name():
return Capital.instance.name()
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
ukraine_capital_1 = Capital("Kyiv")
ukraine_capital_2 = Capital("London")
ukraine_capital_3 = Capital("Marocco")
assert ukraine_capital_2.name() == "Kyiv"
assert ukraine_capital_3.name() == "Kyiv"
assert ukraine_capital_2 is ukraine_capital_1
assert ukraine_capital_3 is ukraine_capital_1
print("Coding complete? Let's try tests!")