add another implementation for lazy property

This commit is contained in:
Alice Wang
2017-07-14 13:30:27 +02:00
parent c6a4c267f8
commit 1cabd302d8
3 changed files with 41 additions and 5 deletions
+1
View File
@@ -1,2 +1,3 @@
__pycache__
*.pyc
.idea
+26
View File
@@ -37,11 +37,23 @@ class lazy_property(object):
return val
def lazy_property2(fn):
attr = '_lazy__' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr):
setattr(self, attr, fn(self))
return getattr(self, attr)
return _lazy_property
class Person(object):
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
self.call_count2 = 0
@lazy_property
def relatives(self):
@@ -49,6 +61,11 @@ class Person(object):
relatives = "Many relatives."
return relatives
@lazy_property2
def parents(self):
self.call_count2 += 1
return "Father and mother"
def main():
Jhon = Person('Jhon', 'Coder')
@@ -58,6 +75,10 @@ def main():
print(u"Jhon's relatives: {0}".format(Jhon.relatives))
print(u"After we've accessed `relatives`:")
print(Jhon.__dict__)
print(Jhon.parents)
print(Jhon.__dict__)
print(Jhon.parents)
print(Jhon.call_count2)
if __name__ == '__main__':
@@ -70,3 +91,8 @@ if __name__ == '__main__':
# Jhon's relatives: Many relatives.
# After we've accessed `relatives`:
# {'relatives': 'Many relatives.', 'name': 'Jhon', 'occupation': 'Coder'}
# Father and mother
# {'_lazy__parents': 'Father and mother', 'relatives': 'Many relatives.',
# 'call_count2': 1, 'name': 'Jhon', 'occupation': 'Coder'}
# Father and mother
# 1
+14 -5
View File
@@ -11,18 +11,27 @@ class TestDynamicExpanding(unittest.TestCase):
self.John = Person('John', 'Coder')
def test_innate_properties(self):
self.assertDictEqual({'name': 'John', 'occupation': 'Coder'},
self.John.__dict__)
self.assertDictEqual(
{'name': 'John', 'occupation': 'Coder', 'call_count2': 0},
self.John.__dict__
)
def test_relatives_not_in_properties(self):
self.assertNotIn('relatives', self.John.__dict__)
def test_extended_properties(self):
print(u"John's relatives: {0}".format(self.John.relatives))
self.assertDictEqual({'name': 'John', 'occupation': 'Coder',
'relatives': 'Many relatives.'},
self.John.__dict__)
self.assertDictEqual(
{'name': 'John', 'occupation': 'Coder',
'relatives': 'Many relatives.', 'call_count2': 0},
self.John.__dict__
)
def test_relatives_after_access(self):
print(u"John's relatives: {0}".format(self.John.relatives))
self.assertIn('relatives', self.John.__dict__)
def test_parents(self):
for _ in range(2):
self.assertEqual(self.John.parents, "Father and mother")
self.assertEqual(self.John.call_count2, 1)