@@ -37,18 +37,35 @@ def __get__(self, obj, type_):
37
37
return val
38
38
39
39
40
+ def lazy_property2 (fn ):
41
+ attr = '_lazy__' + fn .__name__
42
+
43
+ @property
44
+ def _lazy_property (self ):
45
+ if not hasattr (self , attr ):
46
+ setattr (self , attr , fn (self ))
47
+ return getattr (self , attr )
48
+ return _lazy_property
49
+
50
+
40
51
class Person (object ):
41
52
42
53
def __init__ (self , name , occupation ):
43
54
self .name = name
44
55
self .occupation = occupation
56
+ self .call_count2 = 0
45
57
46
58
@lazy_property
47
59
def relatives (self ):
48
60
# Get all relatives, let's assume that it costs much time.
49
61
relatives = "Many relatives."
50
62
return relatives
51
63
64
+ @lazy_property2
65
+ def parents (self ):
66
+ self .call_count2 += 1
67
+ return "Father and mother"
68
+
52
69
53
70
def main ():
54
71
Jhon = Person ('Jhon' , 'Coder' )
@@ -58,6 +75,10 @@ def main():
58
75
print (u"Jhon's relatives: {0}" .format (Jhon .relatives ))
59
76
print (u"After we've accessed `relatives`:" )
60
77
print (Jhon .__dict__ )
78
+ print (Jhon .parents )
79
+ print (Jhon .__dict__ )
80
+ print (Jhon .parents )
81
+ print (Jhon .call_count2 )
61
82
62
83
63
84
if __name__ == '__main__' :
@@ -66,7 +87,11 @@ def main():
66
87
### OUTPUT ###
67
88
# Name: Jhon Occupation: Coder
68
89
# Before we access `relatives`:
69
- # {'name': 'Jhon', 'occupation': 'Coder'}
90
+ # {'call_count2': 0, ' name': 'Jhon', 'occupation': 'Coder'}
70
91
# Jhon's relatives: Many relatives.
71
92
# After we've accessed `relatives`:
72
- # {'relatives': 'Many relatives.', 'name': 'Jhon', 'occupation': 'Coder'}
93
+ # {'relatives': 'Many relatives.', 'call_count2': 0, 'name': 'Jhon', 'occupation': 'Coder'}
94
+ # Father and mother
95
+ # {'_lazy__parents': 'Father and mother', 'relatives': 'Many relatives.', 'call_count2': 1, 'name': 'Jhon', 'occupation': 'Coder'}
96
+ # Father and mother
97
+ # 1
0 commit comments