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

Michael Torrie torriem at gmail.com
Wed Apr 27 22:00:08 EDT 2016


On 04/27/2016 07:12 PM, Christopher Reimer wrote:
> 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
>              }

I am guessing that the reason you are storing state as it's own
dictionary is so that you can pass the state itself to the constructor?

>          else:
>              self._state = state

I'm not sure why you are storing the class name in self._state above,
but keep in mind that this part of the constructor will just reference
whatever was in the passed-in state object, whether it's right or wrong.
 So the value of self._state.class and self._state.notation may or may
not be right, compared to what is set in the previous section if None is
passed in.  Also self._state = state means that the state object passed
will be the self._state object.  Not a copy, but the exact same object.
 So multiple instances could have the exact object as self._state.  Not
sure if this is what you intended or not.

Personally I would ditch the self._state dictionary entirely and store
the state directly as instance attributes.  self.color, self.first_move,
etc.  For the constructor if you want to duplicate another object's
state, just pass the entire object as an argument and copy the
attributes manually, rather than passing around the state dict.

I know you've stated reasons for doing things the way you have, but this
self._state dict smells a bit funny, especially where you have
self._state = state, which means that several instances could have the
exact same state object at the same time and strikes me as mildly
un-pythonic and very confusing.  "State" is what instances themselves
are supposed to track by design.  I recommend you use this feature
rather than duplicating it with your own error-prone dict handling.



More information about the Python-list mailing list