-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_decoration.py
More file actions
97 lines (91 loc) · 3.02 KB
/
class_decoration.py
File metadata and controls
97 lines (91 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def add_getters( obj, pattern = 'get_%s' ):
"""
>>> class A:
... def __init__( self ): self.a = None; self.b = []
... def x( self ): print 'x'
...
>>> a = A()
>>> print dir( a )
['__doc__', '__init__', '__module__', 'a', 'b', 'x']
>>> add_getters( a )
>>> print dir(a)
['__doc__', '__init__', '__module__', 'a', 'b', 'get_a', 'get_b', 'x']
>>> add_getters( a )
>>> print dir(a)
['__doc__', '__init__', '__module__', 'a', 'b', 'get_a', 'get_b', 'x']
>>> a.get_a()
>>> a.get_b()
[]
"""
def getter_creator( name ):
def getter( self_ ):
return getattr( self_, name )
return getter
import new
d = obj.__dict__
getters = [ ( pattern % name, new.instancemethod( getter_creator( name ), obj, obj.__class__ ) )
for name, value in d.items() if not callable( value ) ]
d.update( dict( getters ) )
def add_setters( obj, pattern = 'set_%s' ):
"""
>>> class A:
... def __init__( self ): self.a = None; self.b = []
... def x( self ): print 'x'
...
>>> a = A()
>>> print dir( a )
['__doc__', '__init__', '__module__', 'a', 'b', 'x']
>>> add_setters( a )
>>> print dir(a)
['__doc__', '__init__', '__module__', 'a', 'b', 'set_a', 'set_b', 'x']
>>> add_setters( a )
>>> print dir(a)
['__doc__', '__init__', '__module__', 'a', 'b', 'set_a', 'set_b', 'x']
>>> a.set_a( 1 )
>>> a.a
1
>>> a.set_b( [1,2] )
>>> a.b
[1, 2]
"""
def setter_creator( name ):
def setter( self_, val ):
return setattr( self_, name, val )
return setter
import new
d = obj.__dict__
setters = [ ( pattern % name, new.instancemethod( setter_creator( name ), obj, obj.__class__ ) )
for name, value in d.items() if not callable( value ) ]
d.update( dict( setters ) )
def add_getters_setters( obj ):
"""
>>> class A:
... def __init__( self ): self.a = None; self.b = []
... def x( self ): print 'x'
...
>>> a = A()
>>> print dir( a )
['__doc__', '__init__', '__module__', 'a', 'b', 'x']
>>> add_getters_setters( a )
>>> print dir(a)
['__doc__', '__init__', '__module__', 'a', 'b', 'get_a', 'get_b', 'set_a', 'set_b', 'x']
>>> add_getters_setters( a )
>>> print dir(a)
['__doc__', '__init__', '__module__', 'a', 'b', 'get_a', 'get_b', 'set_a', 'set_b', 'x']
>>> a.get_a()
>>> a.set_a( 1 )
>>> a.get_a()
1
>>> a.get_b()
[]
>>> a.set_b( [1,2] )
>>> a.get_b()
[1, 2]
"""
add_getters( obj )
add_setters( obj )
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()