Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. class Account(object):
  2. def __init__(self, name, balance):
  3. self.name = name
  4. self.balance = balance
  5. self.observers = set()
  6. def __del__(self):
  7. for ob in self.observers:
  8. ob.close()
  9. del self.observers
  10. def register(self, observer):
  11. self.observers.add(observer)
  12. def unregister(self, observer):
  13. self.observers.remove(observer)
  14. def notify(self):
  15. for ob in self.observers:
  16. ob.update()
  17. def withdraw(self, amt):
  18. self.balance -= amt
  19. self.notify()
  20.  
  21.  
  22. class AccountObserver(object):
  23. def __init__(self, theaccount):
  24. self.theaccount = theaccount
  25. self.theaccount.register(self)
  26.  
  27. def __del__(self):
  28. self.theaccount.unregister(self)
  29. del self.theaccount
  30.  
  31. def update(self):
  32. print("Balance is %0.2f" % self.theaccount.balance)
  33.  
  34. def close(self):
  35. print("Account no longer in use")
  36.  
  37.  
  38. a = Account("Ketty", 200000)
  39. a_mama = AccountObserver(a)
  40. a_tata = AccountObserver(a)
  41. a.unregister(a_mama)
  42. a.withdraw(10)
  43.  
  44. Balance is 199990.00
  45. Account no longer in use
  46. Exception ignored in: <bound method AccountObserver.__del__ of <__main__.AccountObserver object at 0x024BF9F0>>
  47. Traceback (most recent call last):
  48. File "F:ProjectsTestPsrcmain.py", line 28, in __del__
  49. File "F:ProjectsTestPsrcmain.py", line 13, in unregister
  50. AttributeError: 'Account' object has no attribute 'observers'
  51. Exception ignored in: <bound method AccountObserver.__del__ of <__main__.AccountObserver object at 0x024BFEB0>>
  52. Traceback (most recent call last):
  53. File "F:ProjectsTestPsrcmain.py", line 28, in __del__
  54. File "F:ProjectsTestPsrcmain.py", line 13, in unregister
  55. AttributeError: 'Account' object has no attribute 'observers'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement