Re: [Tutor] designing POOP

2008-02-11 Thread Tiger12506
> "bhaaluu" <[EMAIL PROTECTED]> wrote
>
>> States, getters-setters, direct access...
>> I'm still in toilet-training here/ 8^D
>> Can you provide some simple examples that
>> illustrate exactly what and why there is any
>> contention at all?

One clear example I can think of that shows the views is this:

Imagine you have a video game. You model it with a class.

class VideoGame:
  pass

But this video game will up your score if you hit this a particular button, 
which means that it needs to a) keep track of its score b) know what to do 
when the button is pushed

class VideoGame:
  def __init__(self):
self.score = 0
  def buttonpush(self):
self.score += 1

This is all fine and dandy, but the video game is pretty worthless unless it 
can show us what the score is. There are two ways to go about this. A) Give 
the video game a display which it updates, or B) Tear open the case of the 
video game and look at the actual gears that increment the score to read it. 
(imagine it's an old, old game - work with me here!)
So, to print, you can...

vg = VideoGame()
howmany = rand.randint(0,100)
for i in range(howmany):
  vg.buttonpush()
  print vg.score#Tear open the case (hope you have a screwdriver)

OR

class VideoGame():
  def __init__(self):
self.score = 0
  def updatedisp():
print self.score
  def buttonpush():
self.score += 1
self.updatedisp()

vg = VideoGame()
howmany = rand.randint(0,100)
for i in range(howmany):
  vg.buttonpush()#Let the videogame display your score 
however it wishes

The second way is preferable for many reasons...
A) The game designer decides to change the display, you don't have to change 
any code that uses the class
B) Clearly, tearing open a videogame is pretty low-level from an object 
perspective. This is what Alan is saying with OOP purism.

Now. Alan's suggestion to have a state method is like... having a sticker on 
the side of the video game that constantly changes to show the internal 
state of the machine. (yeah yeah, stickers change, sure...) Anyway, This is 
very nice from a debugging standpoint, where you find out that the game does 
something incredibly weird, (like after 2**16 buttonpushes it jumps to 
negative numbers), so that you can watch exactly what happens inside the 
machine without tearing it apart. There are a few drawbacks though.
As soon as you change the internal mechanism, the sticker is at a loss 
because it can't tell you the state anymore! So every time you change the 
internals, you have to change the sticker on the outside to reflect that 
change. This is what Kent is trying to say here about the lack of advantage 
to a state method. However, the advantage of pure OOP here is that if the 
videogame model is designed correctly, never would you have to change the 
actual display if you changed how the score was calculated.

Well, I don't know if this whole email was of use, but it makes the crux of 
the argument make sense to me. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing POOP

2008-02-11 Thread Alan Gauld
"bhaaluu" <[EMAIL PROTECTED]> wrote

> States, getters-setters, direct access...
> I'm still in toilet-training here/ 8^D
> Can you provide some simple examples that
> illustrate exactly what and why there is any
> contention at all?

I'll try.

State is just a bit of jargon to describe the combined 
values of an objects attributes. Here is an example:

class Counter(object):
def __init__(self, initial=0, delta=1):
 self.value = initial
 self.delta = delta
def inc(self)
 self.value += delta
 return self.value
def state(self):
 return (self.value,self.delta)

a = Counter()
b = Counter(1)
c = Counter(0,5)

print a.state, b.state, c.state

So all 3 objects have different combinations of values 
so they have different states.
The state determines the value returned by the objects 
inc method

x = a.inc() # x-> 1
y = b.inc() # y -> 2
z = c.inc() # z -> 5

This is fine and dandy but what if we want to find out the 
current value of a.value without calling inc?
Thats where hetter/setter/direct access comes into the 
picture.
In Java and some other languages the idiomatic thing 
to do is provide methods prefixed with get/set for each attribute

class Counter(object):
def __init__(self, initial=0, delta=1):...
def inc(self)...
def state(self):...
def getDelta(self): return self.delta
def getValue(self): return self.value
def setValue(self, val): self.value = val
def setDelta(self, val): self.delta = val

Now this is a lot of typing! It also isn't necessary in Python 
because Python allows you to access the attributes 
diectly - direct access. Like so:

a.delta = 42
a.inc()
print a.value

This gives rise to a debate between the OOP purists who say 
that you should only access the internals of an object via a 
method(get/set) and the pragmatists who say its OK to use 
direct access. And old school OOPers like me say it would 
be better if you didn't need to use either since you should 
define the object in terms of higher level abstractions/methods.

Now, with my pragmatic hat on I see no point whatsoever in 
writing reams of get/set code just for the salke of it, so if you 
must bypass the abstract methods use direct access. But 
what if you want all of the attributes - to print state say?
Thats where the question of direct  access versus a state() 
method comes in. My preference is to provide a single 
method that returns the values that you need (and in many 
cases thats less than all of the attributes!) rather than allowing, 
or even encouraging, direct access.

The danger with direct access is that we use it not only for 
reading but also for directly modifying the attributes - and 
that is a bad OOP habit! (Remember: Objects do it to themselves!) 
For example we want to decrement a counter instead of 
incrementing.

we could do it directly:

c.value = c.value -5

But it would be better to do it in an OOP way.

So the final issue (and Kent will no doubt have more to add 
from his perspective!) is if we do want to modify the Counter 
how do we do it (assuming we don't own the original class 
or too many other projects already use it to risk breaking 
them)? Well, the pure OOP way is by sub classing. 
Thus if we want a counter with a dec() method as well as an 
inc(), we can create one:

class UpDownCounter(Counter):
  def dec(self):
  self.value -= self.delta
  return self.value

Now if we make c an instance of UpDownCounter we can do:

c = UpDownCounter(0,5)
c.inc()
print c.state()
c.dec()
print c.state()

And this has the advantage that there is no impact on the 
other objects derived from the initial Counter class. Note that 
as well as adding methods you can also modify, or change 
entirely, the existing methods, that's called "overriding a method" 
and is probably left for later!

I hope that makes sense, its about the simplest example 
I could come up with.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Python-Help] [EMAIL PROTECTED]

2008-02-11 Thread bob gailer
Artur Sousa wrote:
> What's the difference between:
>
> 
> for a in range(2, 10):
>  for n in range(2, a):
>  if a % n == 0:
>  print a, 'equals', n, '*', a/n
>  break
>  else:
>  print a, 'is a prime number'
> 
>
> and
>
> 
> for a in range(2, 10):
>   for n in range(2, a):
>   if a % n ==0:
>   print a, 'equals', n, '*', a/n
>   break
>   else:
>   print a, 'is a prime number'
> 
>   
Most of us monitor tutor and help - so initially pleas just post to one. 
Tutor is probably the best in this case.

The obvious difference is the placement of the else statement. In the 
first else pairs with for and is invoked when no break happens. In the 
second else pairs with if and is invoked each time the divisor test fails.

If that does not help you decide which is correct (it should) then run 
the 2 programs examine the results and that should reveal which gives 
you what you want.



-- 
Bob Gailer
919-636-4239 Chapel Hill, NC

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Change dictionary value depending on a conditional statement.

2008-02-11 Thread Steve Willoughby
Kent Johnson wrote:
> Try
>list.append({'id': 'name', 'link': ('YY','XX')[total > 0]})

I'd caution against that, though.  It's clever and cute, sure, but the 
meaning of it is obfuscated enough to be unpythonic because [total > 0] 
as a subscript doesn't mean anything unless you know you're taking 
advantage of an implementation detail that booleans are 0 for false and 
1 for true.  No matter how reliable that fact may be, I don't think that 
value should be stuck into a numeric context like that.

> Or, in Python 2.5,
>list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')})

This is much more clear, and would IMHO be fine.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner in need

2008-02-11 Thread Kent Johnson
Artur Sousa wrote:
> Sorry... forgot to add the code...
> 
> 2008/2/11, Artur Sousa <[EMAIL PROTECTED] >:
> 
> 
> Hi. Just started on programming, as well on Python. I'm having a
> little problem:

It helps if you describe the problem. If you are getting an error 
message, copy/paste the entire error message, including the traceback, 
into your email.

> What's the difference between:
> 
>  
> for n in range(2, 10):
>  for x in range(2, n):
>  if n % x == 0:
>  print n, 'equals', x, '*', n/x
>  break
>  else:
>  # loop fell through without finding a factor
>  print n, 'is a prime number'
>  
> and
>  
> 
> for a in range(2, 10):
>   for n in range(2, a):
>   if a % n ==0:

The above line is missing an indent, it needs to be indented more than 
the 'for' line.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Beginner in need

2008-02-11 Thread Artur Sousa
Hi. Just started on programming, as well on Python. I'm having a little
problem:

What's the difference between:


>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner in need

2008-02-11 Thread Artur Sousa
Sorry... forgot to add the code...

2008/2/11, Artur Sousa <[EMAIL PROTECTED]>:
>
>
> Hi. Just started on programming, as well on Python. I'm having a little
> problem:
>



 What's the difference between:
>

for n in range(2, 10):
 for x in range(2, n):
 if n % x == 0:
 print n, 'equals', x, '*', n/x
 break
 else:
 # loop fell through without finding a factor
 print n, 'is a prime number'

and


for a in range(2, 10):
  for n in range(2, a):
  if a % n ==0:
   print a, 'equals', n, '*', a/n
   break
  else:
   print a, 'is a prime number'

each of the first spaces should be a "Tab".












-- 
Sorry for any inconvenience...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Change dictionary value depending on a conditional statement.

2008-02-11 Thread Kent Johnson
bob gailer wrote:
> The terse version:
> 
> list.append({'id': 'name', 'link': ('XX','YY')[total > 0]})

I think you have it backwards:
In [1]: total=0
In [2]: ('XX','YY')[total > 0]
Out[2]: 'XX'
In [3]: total=1
In [4]: ('XX','YY')[total > 0]
Out[4]: 'YY'

Try
   list.append({'id': 'name', 'link': ('YY','XX')[total > 0]})

Or, in Python 2.5,
   list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')})

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Change dictionary value depending on a conditional statement.

2008-02-11 Thread bob gailer
Norman Khine wrote:
> Hello,
> Is there a better way to do this:
>
>  >>> list = []
>  >>> total = 0
>  >>> if total > 0:
> ... x = {'id': 'name', 'link': 'XX'}
> ... list.append(x)
> ... else:
> ... y = {'id': 'name', 'link': 'YY'}
> ... list.append(y)
> ...
>
> I would like to change the key 'link' value depending on the value of 
> 'total' so for example if total == 2, then append x else y to the list.
>   
The terse version:

list.append({'id': 'name', 'link': ('XX','YY')[total > 0]})


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing POOP

2008-02-11 Thread bhaaluu
On Feb 11, 2008 3:49 AM, Alan Gauld <[EMAIL PROTECTED]> wrote:
>
> I think we are in general agreement, albeit with different levels of
> trust/toleration of the technique. Direct access is preferred to
> getter/setter methods but is in turn less desirable that higher
> level methods where they exist. The only contention seems to be
> whether a values() type mutilple-return method is worth anything over
> direct access. My personal taste is that if I need the entire
> "official"
> state of an object I'd like a method to give it me in one piece, but
> others obviously may feel differently.
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld

States, getters-setters, direct access...
I'm still in toilet-training here/ 8^D
Can you provide some simple examples that
illustrate exactly what and why there is any
contention at all?

TIA
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lan with python

2008-02-11 Thread Luke Paireepinart
Treloar, Nick wrote:
> hey i was just wondering if any one could tell me if they know if you 
> can make multi player games through lan with python heres the code i 
> want to lan.
>  
> just hash out the sound files 
>  [snip lots of code]
Hi Nick.
Please don't send huge amounts of code inline in an e-mail.  The chances 
of it coming out correctly are slim.  If you must, use attachments.

Yes, you can create multiplayer games through lan with python.  There 
are many ways to go about this.
You can use the Socket module to do low-level network programming, or 
you can use Twisted for a more robust solution.
There are other alternatives as well.

Might I ask why your code uses Pygame and TKinter together?  Why didn't 
you just code the GUI of your game in Pygame?
Did you use Pygame just because of the sound-playing abilities?
(I don't have time to read it in detail.)
Best wishes,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing POOP

2008-02-11 Thread Alan Gauld
"Kent Johnson" <[EMAIL PROTECTED]> wrote

>> The secondary reason is that a class author should be free
>> to change the internal data of a class provided he doesn't change
>> the message interface, but allowing direct access greatly increases
>> the risk that a change will break some users code. Particularly
>> if the change involves removing an attribute or converting it to a
>> derived value.
>
> That is the usual argument for getters and setters in Java and C++ 
> (at
> least). It makes sense for those languages but it doesn't hold water 
> in
> Python where a simple attribute can be changed to a property with
> whatever underlying functionality you like and no change in client 
> code.

While that's true, it does move the onus onto the class maintainer
to develop backwards compatible properties that may no longer
have any releavance to the internal method code. For example
a circle shape which moves from using a centre+radius system
to one which uses a bounding box, or vice versa. (Although it could
be argued that regardless of the implementation the radius/centre
should be properties of the circle)

But more dangerous is a database access class that stores the
tablename and then changes database schema such that two
names are needed, or vice versa, and direct access to that kind
of attribute would be a very bad smell indeed! Why does the client
need the tablename?!

I think we are in general agreement, albeit with different levels of
trust/toleration of the technique. Direct access is preferred to
getter/setter methods but is in turn less desirable that higher
level methods where they exist. The only contention seems to be
whether a values() type mutilple-return method is worth anything over
direct access. My personal taste is that if I need the entire 
"official"
state of an object I'd like a method to give it me in one piece, but
others obviously may feel differently.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor