File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -37,6 +37,7 @@ Current Patterns:
3737| [ prototype] ( prototype.py ) | use a factory and clones of a prototype for new instances (if instantiation is expensive) |
3838| [ proxy] ( proxy.py ) | an object funnels operations to something else |
3939| [ publish_subscribe] ( publish_subscribe.py ) | a source syndicates events/data to 0+ registered listeners |
40+ | [ registry] ( registry.py ) | keeping track of all subclasses of a given class |
4041| [ specification] ( specification.py ) | business rules can be recombined by chaining the business rules together using boolean logic |
4142| [ state] ( state.py ) | logic is org'd into a discrete number of potential states and the next state that can be transitioned to |
4243| [ strategy] ( strategy.py ) | selectable operations over the same data |
Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+
4+
5+ class RegistryHolder (type ):
6+
7+ REGISTRY = {}
8+
9+ def __new__ (cls , name , bases , attrs ):
10+ new_cls = type .__new__ (cls , name , bases , attrs )
11+ """
12+ Here the name of the class is used as key but it could be any class
13+ parameter.
14+ """
15+ cls .REGISTRY [new_cls .__name__ ] = new_cls
16+ return new_cls
17+
18+ @classmethod
19+ def get_registry (cls ):
20+ return dict (cls .REGISTRY )
21+
22+
23+ class BaseRegisteredClass (metaclass = RegistryHolder ):
24+ """
25+ Any class that will inherits from BaseRegisteredClass will be included
26+ inside the dict RegistryHolder.REGISTRY, the key being the name of the
27+ class and the associated value, the class itself.
28+ """
29+ pass
30+
31+ if __name__ == "__main__" :
32+ print ("Before subclassing: " )
33+ for k in RegistryHolder .REGISTRY :
34+ print (k )
35+
36+ class ClassRegistree (BaseRegisteredClass ):
37+
38+ def __init__ (self , * args , ** kwargs ):
39+ pass
40+ print ("After subclassing: " )
41+ for k in RegistryHolder .REGISTRY :
42+ print (k )
43+
44+ ### OUTPUT ###
45+ # Before subclassing:
46+ # BaseRegisteredClass
47+ # After subclassing:
48+ # BaseRegisteredClass
49+ # ClassRegistree
You can’t perform that action at this time.
0 commit comments