Closed ReisG closed 2 years ago
We can use something like that
class MyBestClass:
__count = 0
def __init__(self) -> None:
MyBestClass.__count += 1
def __new__(cls):
if MyBestClass.__count == 0:
obj = super(MyBestClass, cls).__new__(cls)
return obj
raise SyntaxError(f"You can\'t create more then 1 innstance of {MyBestClass.__name__} class")
I found something interesting about how objects creates:
I've looked though and understood that it can be implemented like this
class Player:
''' It's a singleton class '''
__slots__ = ('name')
created_object = None
def __init__(self, name):
self.name = name
def __new__(cls, *args, **kwargs):
if cls.created_object is None:
cls.created_object = super().__new__(cls)
cls.created_object.__init__(*args, **kwargs)
return cls.created_object
return cls.created_object
You can try to test it with this code
if __name__ == '__main__':
a = Player('Max')
b = Player('Alex')
print(f"a's name is {a.name}")
print(f"b's name is {b.name}")
print(f'a is b == {a is b}')
But don't forget about encapsulation
Don't you think it would be better to turn UserInterface class into singleton. We won't be able to create 2 instances (actually when we will try to make a new one it will return as an existing one)