🐍 python example singleton software design pattern

python

fukurou

the supreme coder
ADMIN
Python:
class PersonSingleton:
    __instance = None

    @staticmethod
    def getInstance(name: str, age: int):
        """ Static access method. """
        if PersonSingleton.__instance == None:
            PersonSingleton(name, age)
        return PersonSingleton.__instance

    def __init__(self, name: str, age: int):
        if PersonSingleton.__instance != None :
            raise Exception("singleton cannot be instantiated more than once")
        else :
            self.name = name
            self.age = age
            PersonSingleton.__instance = self
    @staticmethod
    def toString():
        return f"name :{PersonSingleton.__instance.name}, age: {PersonSingleton.__instance.age}"

s = PersonSingleton.getInstance("johny", 30)
print(s.name)
s2 = PersonSingleton.getInstance("raiden",500)
print(s2.name)
s2.name = "raiden"
s2.age = 500
print(PersonSingleton.toString())
 
Top