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

Christopher Reimer christopher_reimer at yahoo.com
Wed Apr 27 21:12:02 EDT 2016


On 4/26/2016 8:56 PM, Random832 wrote:
> what exactly do you mean by property decorators? If you're just 
> accessing them in a dictionary what's the benefit over having the 
> values be simple attributes rather than properties?

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.

Thank you,

Chris R.



class Piece(object):
     def __init__(self, color, position, state=None):
         if state is None:
             self._state = {
                 'class': self.__class__.__name__,
                 'color': color,
                 'first_move': True,
                 'initial_position': position,
                 'move_count': 0,
                 'name': color.title() + ' ' + self.__class__.__name__,
                 'notation': color.title()[:1] + 
self.__class__.__name__[:1],
                 'position': position
             }
         else:
             self._state = state

     @property
     def color(self):
         return self._state['color']

     def fetch_state(self):
         return self._state

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

     @property
     def move_count(self):
         return self._state['move_count']

     @property
     def name(self):
         return self._state['name']

     @property
     def notation(self):
         return self._state['notation']

     @property
     def position(self):
         return self._state['position']

     @position.setter
     def position(self, position):
         self._state['position'] = position
         if self._state['first_move']:
             self._state['first_move'] = False
         self._state['move_count'] += 1




More information about the Python-list mailing list