Skip to content

Commit 7d86368

Browse files
committed
update Singleton
1 parent 43540b3 commit 7d86368

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

notebooks/PythonObjects-Singleton.ipynb

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,7 +1013,6 @@
10131013
"- since python doesn't have a private access specifier, we've to be a little creative\n",
10141014
"- can use `__new__()` method and class variable to ensure that only one instance is created\n",
10151015
"- 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",
10171016
"- `__new__()` is a class method that is called before the `__init__()` instance method\n",
10181017
"- use `cls` parameter to check if the instance is already created\n",
10191018
"- return the instance if it's already created\n",
@@ -1031,25 +1030,28 @@
10311030
"source": [
10321031
"from __future__ import annotations\n",
10331032
"\n",
1033+
"\n",
10341034
"class MySingletonClass:\n",
1035-
" _instance: \"MyClass\" | None = None\n",
1035+
" _instance: \"MySingletonClass\" | None = None\n",
10361036
"\n",
10371037
" # singleton pattern\n",
10381038
" def __new__(cls, *args, **kwargs):\n",
10391039
" # 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",
10411041
" if not cls._instance:\n",
10421042
" cls._instance = super().__new__(cls, *args, **kwargs)\n",
10431043
" return cls._instance\n",
10441044
"\n",
1045-
" def __init__(self, a, b):\n",
1045+
" def __init__(self, a: int, b: int) -> None:\n",
10461046
" self.a = a\n",
10471047
" self.b = b\n",
10481048
"\n",
1049-
" def __str__(self):\n",
1049+
" def __str__(self) -> str:\n",
10501050
" 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",
10531055
" return self.a == other.a and self.b == other.b"
10541056
]
10551057
},

0 commit comments

Comments
 (0)