@@ -37,18 +37,35 @@ def __get__(self, obj, type_):
3737 return val
3838
3939
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+
4051class Person (object ):
4152
4253 def __init__ (self , name , occupation ):
4354 self .name = name
4455 self .occupation = occupation
56+ self .call_count2 = 0
4557
4658 @lazy_property
4759 def relatives (self ):
4860 # Get all relatives, let's assume that it costs much time.
4961 relatives = "Many relatives."
5062 return relatives
5163
64+ @lazy_property2
65+ def parents (self ):
66+ self .call_count2 += 1
67+ return "Father and mother"
68+
5269
5370def main ():
5471 Jhon = Person ('Jhon' , 'Coder' )
@@ -58,6 +75,10 @@ def main():
5875 print (u"Jhon's relatives: {0}" .format (Jhon .relatives ))
5976 print (u"After we've accessed `relatives`:" )
6077 print (Jhon .__dict__ )
78+ print (Jhon .parents )
79+ print (Jhon .__dict__ )
80+ print (Jhon .parents )
81+ print (Jhon .call_count2 )
6182
6283
6384if __name__ == '__main__' :
@@ -66,7 +87,11 @@ def main():
6687### OUTPUT ###
6788# Name: Jhon Occupation: Coder
6889# Before we access `relatives`:
69- # {'name': 'Jhon', 'occupation': 'Coder'}
90+ # {'call_count2': 0, ' name': 'Jhon', 'occupation': 'Coder'}
7091# Jhon's relatives: Many relatives.
7192# 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