Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #107737
| From | Christopher Reimer <christopher_reimer@icloud.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Differences between Class(Object) and Class(Dict) for dictionary usage? |
| Date | 2016-04-27 18:12 -0700 |
| Message-ID | <mailman.155.1461805991.32212.python-list@python.org> (permalink) |
| References | <57216399.1050702@icloud.com> |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Differences between Class(Object) and Class(Dict) for dictionary usage? Christopher Reimer <christopher_reimer@icloud.com> - 2016-04-27 18:12 -0700
csiph-web