Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #107744
| From | Ethan Furman <ethan@stoneleaf.us> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Differences between Class(Object) and Class(Dict) for dictionary usage? |
| Date | 2016-04-27 20:05 -0700 |
| Message-ID | <mailman.162.1461812654.32212.python-list@python.org> (permalink) |
| References | <57216399.1050702@icloud.com> <57217DF7.1030509@stoneleaf.us> |
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~
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Differences between Class(Object) and Class(Dict) for dictionary usage? Ethan Furman <ethan@stoneleaf.us> - 2016-04-27 20:05 -0700
csiph-web