Page 230 -
P. 230

idle session







              Let’s use IDLE to create some object instances from a new class that you’ll define. Start by creating a small class
              called Athlete:
                                                                        Note the default values for
              >>> class Athlete:                                        two of the arguments.
                     def __init__(self, a_name, a_dob=None, a_times=[]):
                             self.name = a_name         Three attributes are initialized and assigned to three class
                             self.dob = a_dob           attributes using the supplied argument data.
                             self.times = a_times
              With the class defined, create two unique object instances which derive their characteristcs from the Athlete
              class:
              >>> sarah = Athlete('Sarah Sweeney', '2002-6-17', ['2:58', '2.58', '1.56'])
              >>> james = Athlete('James Jones')
                                                                           Create two unique athletes (with
              >>> type(sarah)                                              “james” using the default argument
              <class '__main__.Athlete'>     Confirm that both “sarah” and   values).
              >>> type(james)                “james” are athletes.
              <class '__main__.Athlete'>
              Even though sarah and james are both athletes and were created by the Athlete class’s factory function,
              they are stored at different memory addreses:
              >>> sarah
                                                        differ from the values reported on yours. The key point is
              <__main__.Athlete object at 0x14d23f0>    These are the memory addresses on our computer, which will
              >>> james                                 the memory address for “sarah” and “james” differ.
              <__main__.Athlete object at 0x14cb7d0>

              Now that sarah and james exist as object instances, you can use the familiar dot notation to access the
              attributes associated with each:

              >>> sarah.name
              'Sarah Sweeney'
              >>> james.name
              'James Jones'
              >>> sarah.dob
              '2002-6-17'
              >>> james.dob           The “james” object instance has no value for
                                      “dob”, so nothing appears on screen.
              >>> sarah.times
              ['2:58', '2.58', '1.56']
              >>> james.times
              []



           194    Chapter 6
   225   226   227   228   229   230   231   232   233   234   235