Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Singleton Pattern implementation in Python #6800

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions code/design_pattern/src/singleton_pattern/singleton_pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class SingletonClass:
_instance = None

def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SingletonClass, cls).__new__(
cls, *args, **kwargs
)

return cls._instance

def foo(self):
print("bar")


# Usage
s1 = SingletonClass()
s2 = SingletonClass()

print(s1 is s2) # Output: True, both refer to the same instance

s1.foo() # Output: bar
s2.foo() # Output: bar