Sunday, January 31, 2016

w3d5 - 2 days late with a reality check on OOP

Well, that was brutal.

I left off Thursday evening with grand plans for a general card game constructor. I limped in to Sunday night with a functional blackjack game built with python classes.  The basic structures I outlined survived.  I learned some good lessons in debugging long scripts, step-wise validation of functional code, and yet another lesson on data structures.

On data structures and class variables: be cautious.  Using

class Player(object):
      def __init__(self, name='', data=[]):
             self.name = name
             self.data = data

looks to the naive as though it will save some key strokes when initializing instances .  As it turns out, each instance of Player has different name, but their self.data points to the same list.  E.g.:

>>>bob = Player(name='bob')
>>>jeff = Player(name='jeff')
>>>
>>>bob.data.append('yo')
>>>
>>>jeff.name
>>>'jeff'
>>>jeff.data
>>>['yo']

It recalls the points raised in this Stack Overflow thread on how to be a good programmer (specifically wscpy's answer highlighting the difference between how python stores integers or strings and how it stores(references) lists).

I have so much to learn about the stuff under the hood.

On debugging:

I have more lines devoted to test prints for individual functions (to monitor what various pieces of the script are doing) that I had in any program I wrote before I got to camp.  Still small relative to 'real' stuff, but still...

And also - even when you think you know what you're doing, test shit.  I might get that as a tattoo and save myself a ton of future pain.


No comments:

Post a Comment