The Critter Program
The following is a very simple program that demonstrates creating an instance of a class.
The class also contains:
__init__()
- constructor for the class.total
- a class attribute which tracks the number of instances of the class created.status
- a static method that prints out how many instances of the class are created using the class attributetotal
.
class Critter:
"""A virtual critter class"""
total = 0
def __init__(self, name):
print("A critter has been born!")
self.name = name
Critter.total += 1
# this stops the first argument being the instance
@staticmethod
def status():
print("\nThe total number of critters is", Critter.total)
def main():
print("Accessing the class attribute Critter.total:", end=" ")
print(Critter.total)
print("\nCreating critters.")
crit_one = Critter("critter 1")
crit_two = Critter("critter 2")
crit_three = Critter("critter 3")
Critter.status()
print("\nAccessing the class attribute through an object:", end= " ")
print(crit_one.total)
input("\n\nPress the enter key to exit.")
if __name__ == "__main__":
main()