From 0257c034bab2f8c9b660d1c31b141f2edc072403 Mon Sep 17 00:00:00 2001 From: Pavan Date: Tue, 26 Oct 2021 21:04:36 +0530 Subject: [PATCH] Create learn_singleton.py --- .../Python_Programs/learn_singleton.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Program's_Contributed_By_Contributors/Python_Programs/learn_singleton.py diff --git a/Program's_Contributed_By_Contributors/Python_Programs/learn_singleton.py b/Program's_Contributed_By_Contributors/Python_Programs/learn_singleton.py new file mode 100644 index 0000000000..9fffaaf3b8 --- /dev/null +++ b/Program's_Contributed_By_Contributors/Python_Programs/learn_singleton.py @@ -0,0 +1,30 @@ +def singleton(class_): + instances = {} + def getinstance(*args, **kwargs): + if class_ not in instances: + instances[class_] = class_(*args, **kwargs) + return instances[class_] + return getinstance + +@singleton +class Test1(object): + def __init__(self): + self.var_1 = "bob" + + def change_var(self, new_var): + print(self.var_1) #should print "bob" + self.var_1 = new_var #should change "bob" to "john" + print(self.var_1) #should print "john" + +class Test2(object): + def __init__(self): + test1 = Test1() + test1.change_var("john") + +class Test3(object): + def __init__(self): + test1 = Test1() + print(test1.var_1) + +Test2() +Test3()