File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ A class that uses different static function depending of a parameter passed in init
3
+ Note the use of a single dictionnary instead of multiple conditions
4
+ """
5
+ __author__ = "Ibrahim Diop <http://ibrahim.zinaria.com>"
6
+ __gist__ = "<https://gist.github.com/diopib/7679559>"
7
+
8
+ class Catalog ():
9
+ """
10
+ catalog of multiple static methods that are executed depending on an init parameter
11
+ """
12
+
13
+ def __init__ (self , param ):
14
+
15
+ # dictionary that will be used to determine which static method is to be executed but
16
+ # that will be also used to store possible param value
17
+ self .static_method_choices = {'param_value_1' : self .static_method_1 , 'param_value_2' : self .static_method_2 }
18
+
19
+ # simple test to validate param value
20
+ if param in self .static_method_choices .keys ():
21
+ self .param = param
22
+ else :
23
+ raise Exception ("Invalid Value for Param: {0}" .format (param ))
24
+
25
+ @staticmethod
26
+ def static_method_1 ():
27
+ print ("executed method 1!" )
28
+
29
+ @staticmethod
30
+ def static_method_2 ():
31
+ print ("executed method 2!" )
32
+
33
+ def main_method (self ):
34
+ """
35
+ will execute either static_method_1 or static_method_2
36
+ depending on self.param value
37
+ """
38
+ self .static_method_choices [self .param ]()
39
+
40
+
41
+ def main ():
42
+ """
43
+ >>> c = Catalog('param_value_1').main_method()
44
+ executed method 1!
45
+ >>> Catalog('param_value_2').main_method()
46
+ executed method 2!
47
+ """
48
+
49
+ test = Catalog ('param_value_2' )
50
+ test .main_method ()
51
+
52
+ if __name__ == "__main__" :
53
+ main ()
You can’t perform that action at this time.
0 commit comments