|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +classCounter: |
| 4 | + |
| 5 | +def__init__(self,start_value=0): |
| 6 | +# counter always has to start at 0 |
| 7 | +ifstart_value>0: |
| 8 | +self._count=start_value |
| 9 | +else: |
| 10 | +self._count=0 |
| 11 | + |
| 12 | +defincrement(self): |
| 13 | +self._count+=1 |
| 14 | +returnself._count |
| 15 | + |
| 16 | +defdecrement(self): |
| 17 | +# counter cannot go below 0 |
| 18 | +ifself._count-1<0: |
| 19 | +self._count=0 |
| 20 | +else: |
| 21 | +self._count-=1 |
| 22 | +returnself._count |
| 23 | + |
| 24 | + |
| 25 | +classNamer: |
| 26 | + |
| 27 | +def__init__(self,name,age): |
| 28 | +self._name=name |
| 29 | +self._age=age |
| 30 | + |
| 31 | +def__str__(self): |
| 32 | +return"[ {} ]: name={} age={}".format( |
| 33 | +self.__class__, |
| 34 | +self._name, |
| 35 | +self._age, |
| 36 | + ) |
| 37 | + |
| 38 | +defsay_my_name(self): |
| 39 | +# NOTE: this calls the __str__ override method |
| 40 | +print(self) |
| 41 | + |
| 42 | +defcountdown(self): |
| 43 | +age_counter=Counter(start_value=self._age) |
| 44 | +next_age=age_counter._count |
| 45 | +whilenext_age>0: |
| 46 | +print(next_age) |
| 47 | +next_age=age_counter.decrement() |
| 48 | +print("[ DONE ]") |
| 49 | + |
| 50 | +defshow_me_my_data_guts(self): |
| 51 | +# |
| 52 | +# A Python class is just a fancy wrapper |
| 53 | +# around a dictionary. It has special ways to access |
| 54 | +# the dictionary internally from the class. So we can |
| 55 | +# do things such as this to get an internal view of the class |
| 56 | +# |
| 57 | +return"{}".format(self.__dict__) |