|
1013 | 1013 | "- since python doesn't have a private access specifier, we've to be a little creative\n", |
1014 | 1014 | "- can use `__new__()` method and class variable to ensure that only one instance is created\n", |
1015 | 1015 | "- also called anti-pattern because there is only one instance of the class\n", |
1016 | | - "- use `__new__()` method to create a new instance of the class\n", |
1017 | 1016 | "- `__new__()` is a class method that is called before the `__init__()` instance method\n", |
1018 | 1017 | "- use `cls` parameter to check if the instance is already created\n", |
1019 | 1018 | "- return the instance if it's already created\n", |
|
1031 | 1030 | "source": [ |
1032 | 1031 | "from __future__ import annotations\n", |
1033 | 1032 | "\n", |
| 1033 | + "\n", |
1034 | 1034 | "class MySingletonClass:\n", |
1035 | | - " _instance: \"MyClass\" | None = None\n", |
| 1035 | + " _instance: \"MySingletonClass\" | None = None\n", |
1036 | 1036 | "\n", |
1037 | 1037 | " # singleton pattern\n", |
1038 | 1038 | " def __new__(cls, *args, **kwargs):\n", |
1039 | 1039 | " # we don't care about (a, b) so use args and kwargs within __new__\n", |
1040 | | - " # not providing them will create syntax error because __init__ is defined with two arguments \n", |
| 1040 | + " # not providing them will create syntax error because __init__ is defined with two arguments\n", |
1041 | 1041 | " if not cls._instance:\n", |
1042 | 1042 | " cls._instance = super().__new__(cls, *args, **kwargs)\n", |
1043 | 1043 | " return cls._instance\n", |
1044 | 1044 | "\n", |
1045 | | - " def __init__(self, a, b):\n", |
| 1045 | + " def __init__(self, a: int, b: int) -> None:\n", |
1046 | 1046 | " self.a = a\n", |
1047 | 1047 | " self.b = b\n", |
1048 | 1048 | "\n", |
1049 | | - " def __str__(self):\n", |
| 1049 | + " def __str__(self) -> str:\n", |
1050 | 1050 | " return f'{self.a}, {self.b}'\n", |
1051 | | - " \n", |
1052 | | - " def __eq__(self, other):\n", |
| 1051 | + "\n", |
| 1052 | + " def __eq__(self, other: object) -> bool:\n", |
| 1053 | + " if not isinstance(other, MySingletonClass):\n", |
| 1054 | + " return NotImplemented\n", |
1053 | 1055 | " return self.a == other.a and self.b == other.b" |
1054 | 1056 | ] |
1055 | 1057 | }, |
|
0 commit comments