"Battleship" style game

Falstaff mheslep at gmail.com
Thu Mar 26 20:24:09 CET 2009

On Feb 25, 10:11 pm, Zvezdan Petkovic <zvez... at zope.com> wrote:
> On Feb 25, 2009, at 3:54 PM, Shawn Milochik wrote:
> > It is true that it would be fewer lines of code with the same
> > functionality, but it's better practice to have that framework in
> > place so that any changes made in the future wouldn't break any of the
> > code accessing my class. Obviously this is a fairly simple game that
> > has a fixed set of rules, but I'm trying to cultivate good habits, and
> > I don't think that doing it this way is anti-Pythonic.
> Well, they are trying to help you with the best practices.
> You offered the code for review and they reviewed it.
> Whether you'll accept what they say or deny it is your call, of course.
> FWIW, the Pythonic way would be:
>  >>> class Ship(object):
> ...     def __init__(self, length):
> ...         self._length = length
> ...     @property
> ...     def length(self):
> ...         return self._length
> ...
>  >>> s = Ship(5)
>  >>> s.length
> 5
>  >>> # notice how the property is read-only which is what you wanted
>  >>> s.length = 7
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> AttributeError: can't set attribute
>  >>> ^D
> Using @property decorator makes a read-only property.  If you need a  
> read/write property there are several ways to define setter and  
> deleter methods with or without decorators.
> I hope you see that
>         x = s.length
>         s.position = y
> is a completely different style than
>         x = s.get_length()
>         s.set_position(y)
> Most of the people who program in Python prefer the first style above.

I certainly didn't expect this thread to end like this.  Sure, most
Python people prefer properties over straight accessors, but that is
just reworking the methods in the class, and not the reworking the
object model itself.  Thus stopping at 'use properties' misses out on
the one, true promised land of data encapsulation. See e.g.

    "Why getter and setter methods are evil"
    ...Don't ask for the information you need to do the work;
    ask the object that has the information to do the work for you...
    Allen Holub

or any other number of OO references on data encapsulation. This can
even apply to GUI objects now - rather than having the GUI object pull
data from the model object, you have the model draw itself w/ a
draw_myself method, perhaps implemented by a handler.

That goes for Java too, AFAIK.

More information about the Python-list mailing list