Differences between Class(Object) and Class(Dict) for dictionary usage?

Ethan Furman ethan at stoneleaf.us
Wed Apr 27 23:05:27 EDT 2016


On 04/27/2016 06:12 PM, Christopher Reimer wrote:

> After considering the feedback I got for sanity checking my code, I've
> decided to simplify the base class for the chess pieces (see code
> below). All the variables are stored inside a dictionary with most
> values accessible through properties. A custom dictionary can be loaded
> through the constructor and or saved out through the fetch_state method.
> The subclasses only have to implement the is_move_valid method, which is
> different for each type of chess piece.

Much better.

Here's my take on it:

class Piece(object):
     def __init__(self, color, position):
          self._color = color
          self._first_move = True
          self._initial_position = position
          self._move_count = 0
          self._name = color.title() + ' ' + self.__class__.__name__
          self._notation = color.title()[:1] + self.__class__.__name__[:1]
          self._position = position

     @property
     def color(self):
         return self._color

     def is_move_valid(self, new_position, board_state):
         raise NotImplementedError

     @property
     def move_count(self):
         return self._move_count

     @property
     def name(self):
         return self._name

     @property
     def notation(self):
         return self._notation

     @property
     def position(self):
         return self._position

     @position.setter
     def position(self, position):
         self._position = position
         if self._first_move:
             self._first_move = False
         self._move_count += 1

Now all the attributes are, well, attributes of the instance (that's 
what instances are for).

I ripped out the fetch_state because that will take more work -- you 
can't pass a Pawn's saved state in to Piece and get the results you 
want.  pickle is worth looking at for saving/restoring.

Also, your code will give the same notation to Kings and Knights.

--
~Ethan~



More information about the Python-list mailing list