[Tutor] no error no result

2005-11-06 Thread Shi Mu
when I read some python sample codes.
I found that several of them need "python -i" to run them or you will
not get any result though the program does not report any error.
I really can not understand it.
Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] click and line

2005-11-06 Thread Chris F.A. Johnson
On Sun, 6 Nov 2005, Shi Mu wrote:

> frame = c needs to be put before the click function or the lines can
> not be drawn.

 Not at all. I have everything after the click function and it works.

 This is my version (includes a small addition):

def click(event):
 global lastX, lastY
 if lastX != "":
 c.create_line(lastX,lastY,event.x,event.y,fill="white")
 lastX = event.x
 lastY = event.y

def newline(event):
 global lastX, lastY
 lastX=""
 lastY=""

from Tkinter import *

lastX=""
lastY=""
root = Tk()
c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
frame = c
c.bind('',click)
c.bind('',newline)

c.pack()

root.mainloop()

> On 11/6/05, Chris F.A. Johnson <[EMAIL PROTECTED]> wrote:
>> On Sun, 6 Nov 2005, Shi Mu wrote:
>>
>>> based on the following rewritten code, why the lines still can not be
>>> drawn? (there is no error report and the canvas appears).
>>
>> It works for me.
>>
>>
>>> from Tkinter import *
>>>
>>> root = Tk()
>>>
>>> c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
>>>
>>> lastX=""
>>> lastY=""
>>> def click(event):
>>>  global lastX, lastY
>>>  if lastX != "":
>>> c.create_line(lastX,lastY,event.x,event.y,fill="white")
>>>  lastX = event.x
>>>  lastY = event.y
>>>
>>> frame = c
>>> c.bind('',click)
>>>
>>> c.pack()
>>>
>>> root.mainloop()


-- 
 Chris F.A. Johnson 
 ==
 Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] click and line

2005-11-06 Thread Shi Mu
frame = c needs to be put before the click function or the lines can
not be drawn.

On 11/6/05, Chris F.A. Johnson <[EMAIL PROTECTED]> wrote:
> On Sun, 6 Nov 2005, Shi Mu wrote:
>
> > based on the following rewritten code, why the lines still can not be
> > drawn? (there is no error report and the canvas appears).
>
> It works for me.
>
>
> > from Tkinter import *
> >
> > root = Tk()
> >
> > c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
> >
> > lastX=""
> > lastY=""
> > def click(event):
> >  global lastX, lastY
> >  if lastX != "":
> > c.create_line(lastX,lastY,event.x,event.y,fill="white")
> >  lastX = event.x
> >  lastY = event.y
> >
> > frame = c
> > c.bind('',click)
> >
> > c.pack()
> >
> > root.mainloop()
>
> --
> Chris F.A. Johnson 
> ==
> Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] click and line

2005-11-06 Thread Chris F.A. Johnson
On Sun, 6 Nov 2005, Shi Mu wrote:

> based on the following rewritten code, why the lines still can not be
> drawn? (there is no error report and the canvas appears).

 It works for me.


> from Tkinter import *
>
> root = Tk()
>
> c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
>
> lastX=""
> lastY=""
> def click(event):
>  global lastX, lastY
>  if lastX != "":
> c.create_line(lastX,lastY,event.x,event.y,fill="white")
>  lastX = event.x
>  lastY = event.y
>
> frame = c
> c.bind('',click)
>
> c.pack()
>
> root.mainloop()

-- 
 Chris F.A. Johnson 
 ==
 Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Object instances

2005-11-06 Thread Alan Gauld
> I'm not sure what language you've dealt with before, but if it was Java or
> C++, then you've run into Python's variant of static members.
>
> class X(object):
>classMember = True
>
>def __init__(self):
>self.instanceMember = True
>
>
> Does that make it any clearer? As to the why, I'd ask Guido Van Rossum. ;)

Its a standard feature of the Object Model of programming.
Virtally all OOP systems provide a mechanism for setting class level 
attributes.

Alan G. 

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


Re: [Tutor] Object instances

2005-11-06 Thread Alan Gauld
>I had thought I was developing a clue regarding objects in Python, but I
> ran across an oddity today that I didn't expect.  It had seemed to me
> that once an instance was created, it would have a separate data pool
> from any other instance of the same object.

And this is true...

> It would share methods, of course, but the data assigned to it would
> be totally separate.

The data assigned top the instance is separate but you can also assign
data to classes. Such data is stored in "class variables". Class variables
are shared by all instances and indeed can be accessed even when no
instances exist. Methods are a special type of class variable. This all
comes under the black art known as "Meta Programming".

> I would like to understand why not.  I think I'm missing something kind
> of fundamental here.

Its very useful to know things about the class as an entirety. For example
a class variable can be used to keep track of the total number of instances
alive at any one time, or of standard lists of values that are valid for a
variable type (subsets of colors or max/min range values etc)

> The following is my toy example:

> In [1]: class test(object):
>   ...: testlist = []

This is a class variable because its not distinguished by self (self is
unique to each instance).

> In [2]: c1 = test()
>
> In [3]: c1.testlist.append(0)
>
> In [4]: c2 = test()
>
> In [5]: c2.testlist
> Out[5]: [0]
> In this example, I create two instances of the object test, assigned
> data to c1.testlist and it shows up in the other instance, c2.

But you can also override that with

c2.testlist = [1,2,3]

c1.testlist
[0]
c2.testlist
[1,2,3]
c3 = test()
c3.testlist
[0]

So now c2 has its own copy of testlist...

> Typically, I have been assigning values within an object from being
> passed in via __init__, but it seemed like it wasn't really necessary
> for this particular kind of object.

It is if you want the values to be instance specific.

> In [10]: class test(object):
>   : def __init__(self):
>   : self.testlist = []

Now you are creating instance variables by assigning them with self.

> instances, if I ever had to do something like that.  I just don't have a
> clue as to why objects were designed this way.

Look up class variables (and static varoiables - their name in C++
and some other languages) on Google or  http://www.cetus-links.org

HTH<

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] Pygame - was How I use images in a GUI?

2005-11-06 Thread Liam Clarke-Hutchinson
Title: Message



Hi Nathan, 
 
Pygame is a little confusing at first, but 
it makes sense one you can get the hang of the basics. 
 
http://www.pygame.org/docs/tut/intro/intro.html is 
a good example.
 
import sys, pygamepygame.init()size = width, height = (320, 240)speed = [2, 
2]black = (0, 0, 0) screen = 
pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")ballrect = 
ball.get_rect()
 
That's the basic ingredients of a Pygame app 
right there. 
 
screen is the base window that all your 
drawing will occur on.
!A caveat here is that (0,0) on computer 
screens tends to be the top left corner, with y increasing 
downwards.!
 
ball is a Surface which is painted with the 
image at http://www.pygame.org/docs/tut/intro/ball.gif.
ballrect is a Rect object which is 
rectangular and matches the size of the ball (as much as a rectangle 
can.)
 
Rects and Surfaces are the key to Pygame. If 
you had a pygame app where two cars crashed into each other, all movement and 
collision detection is being done with two rects, which have a car drawn on top 
of them via a Surface. You can of course, use many smaller rects, to give 
more accurate collision detection.
 
i.e. for a stick figure, you could have one 
rectangle which was matched the height and width of the whole stick figure. 

Or, you could have one for each arm, one for 
each leg, one for the body and one for the head, which would allow for more 
accurate collision checking. If you've ever played a fps and shot someone in the 
head and blood came out of their body, then you've met rects in action, and not 
quite working properly too. 
 
I tried having 786,432 rects at one point, 
each one was one pixel in size. Didn't work overly well.
 
Surfaces are images/colours/textures etc. I 
consider it like this, the rect is an invisible wireframe, the surface is the 
nice shiny textures and colours all over it. 
 
OK, to continue with the Pygame tutorial - 


while 
1: for event in 
pygame.event.get():if 
event.type == pygame.QUIT: sys.exit()ballrect 
= ballrect.move(speed)if 
ballrect.left < 0 or ballrect.right > width:speed[0] 
= -speed[0]if 
ballrect.top < 0 or ballrect.bottom > height:speed[1] 
= -speed[1]screen.fill(black)    
screen.blit(ball, ballrect)pygame.display.flip()
-for event in pygame.event.get(): if event.type == pygame.QUIT: 
sys.exit()
 
So once the set up is done, Pygame goes into 
an infinite loop. Once per loop, it checks for a Pygame event of type QUIT. 
Pygame handles events a bit like a GUI, in that it has a queue, but programmes 
need to specifically check for events as opposed to using event handlers - it's 
a game, so you can focus on events that are important to you. ;)
 
ballrect = 
ballrect.move(speed)
Ok, so now it's moving ballrect. If you have 
a look at http://www.pygame.org/docs/ref/rect.html there's 
a lot of methods which basically equate to moving/resizing/colliding the Rect. 

 
The command Rect.move() has the following 
syntax - 
 
Rect.move(x, y): 
return Rect
 
Game programming involves a fair bit of 
physics. At the most basic, you'll get to deal with vectors. 
So, ballrect = 
ballrect.move((2,2)) returns a new Rect two pixels to the right, and two 
pixels downward.
 
OK, so, ballrect has moved 2 down and 2 
across.
 
if ballrect.left 
< 0 or ballrect.right > width:speed[0] 
= -speed[0] if ballrect.top < 0 or ballrect.bottom 
> height:speed[1] 
= -speed[1]
ballrect.left, ballrect.right, top, bottom 
etc. are the edges of ballrect. So, this is checking to see if it has exceeded 
the limits of the screen. Now, this is very simple collision checking. A fun 
exercise is to add a second ball, and check once per loop using 
Rect.colliderect(otherRect) to see if they just hit. 
 
OK, so if ballrect.left is less than 0, or 
ballrect.right is greater than the 320, then the horizontal vector is inverted. 
So a movement of 5 becomes -5, which would start moving left. Likewise, if it 
was -5 then it would become -(-5) which is 5. 
 
Ditto also with top and bottom, except that 
-y is moving upwards towards 0, and y is moving downwards 240. Remember, 0,0 is 
top left. I had to stick a note to my screen with that on it.
 
OK now to the last bit of code - 
 
screen.fill(black)    
screen.blit(ball, ballrect)pygame.display.flip()
 
Ok, so, ballrect has been moved to the new position, so we need to 
remove the old drawing of ballrect, and redraw the ball at the new position, to 
simulate movement; like a cartoon. 
screen.fill(black) fills the main screen with a solid colour, which 
over-writes the old drawing of the ball. 
screen.blit(ball, ballrect) then draws the image of the ball onto 
the frame of the ballrect.
 
Lastly, pygame.display.flip() 'flips' the display. When 
you're looking at one frame, pygame is busy drawing the screen in memory. When 
you call flip() it

Re: [Tutor] click and line

2005-11-06 Thread Shi Mu
it works now.

from Tkinter import *

root = Tk()

c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
frame = c
lastX=""
lastY=""
def click(event):
  global lastX, lastY
  if lastX != "":
 c.create_line(lastX,lastY,event.x,event.y,fill="white")
  lastX = event.x
  lastY = event.y


c.bind('',click)

c.pack()

root.mainloop()

On 11/6/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> based on the following rewritten code, why the lines still can not be
> drawn? (there is no error report and the canvas appears).
>
> from Tkinter import *
>
> root = Tk()
>
> c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
>
> lastX=""
> lastY=""
> def click(event):
>  global lastX, lastY
>  if lastX != "":
> c.create_line(lastX,lastY,event.x,event.y,fill="white")
>  lastX = event.x
>  lastY = event.y
>
> frame = c
> c.bind('',click)
>
> c.pack()
>
> root.mainloop()
>
> On 11/6/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> >
> > Hi Shi Mu,
> >
> > Let's look at click():
> >
> > ##
> > def click(event):
> >print event.x, event.y
> >m1=event.x
> >n1=event.y
> > ##
> >
> > By default, variable names in functions are local.  Do you know about
> > local vs global variables?  The assignments to m1 and n1 won't be
> > remembered once we come out of the click() function.
> >
> >
> > It sounds like you want a function-like thing that remembers the very last
> > event we passed to it before.  One way to do this is to use globals,
> > because globals last beyond function calls.
> >
> > For example:
> >
> > ##
> > >>> n = None
> > >>> def lastNumber(x):
> > ... global n
> > ... print "I last saw", n
> > ... n = x
> > ...
> > >>> lastNumber(42)
> > I last saw None
> > >>> lastNumber(17)
> > I last saw 42
> > >>> lastNumber(3)
> > I last saw 17
> > ##
> >
> > So for something very simple, using a global will probably be easiest.
> >
> >
> > However, there are other approaches that don't use globals. One that fits
> > Python's model well is to use a class instance, since instances can store
> > state:
> >
> > ##
> > >>> class LastNumber:
> > ... def __init__(self):
> > ... self.n = None
> > ... def getAndSet(self, x):
> > ... value = self.n
> > ... self.n = x
> > ... return value
> > ...
> > >>> last = LastNumber()
> > >>> last.getAndSet(42)
> > >>> last.getAndSet(3)
> > 42
> > >>> last.getAndSet(7)
> > 3
> > >>> last.getAndSet(9)
> > 7
> > ##
> >
> >
> > Does this make sense?  Please feel free to ask questions here.
> >
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] click and line

2005-11-06 Thread Shi Mu
based on the following rewritten code, why the lines still can not be
drawn? (there is no error report and the canvas appears).

from Tkinter import *

root = Tk()

c = Canvas(root, bg='#0e2e0e', height=500, width=1000)

lastX=""
lastY=""
def click(event):
  global lastX, lastY
  if lastX != "":
 c.create_line(lastX,lastY,event.x,event.y,fill="white")
  lastX = event.x
  lastY = event.y

frame = c
c.bind('',click)

c.pack()

root.mainloop()

On 11/6/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
> Hi Shi Mu,
>
> Let's look at click():
>
> ##
> def click(event):
>print event.x, event.y
>m1=event.x
>n1=event.y
> ##
>
> By default, variable names in functions are local.  Do you know about
> local vs global variables?  The assignments to m1 and n1 won't be
> remembered once we come out of the click() function.
>
>
> It sounds like you want a function-like thing that remembers the very last
> event we passed to it before.  One way to do this is to use globals,
> because globals last beyond function calls.
>
> For example:
>
> ##
> >>> n = None
> >>> def lastNumber(x):
> ... global n
> ... print "I last saw", n
> ... n = x
> ...
> >>> lastNumber(42)
> I last saw None
> >>> lastNumber(17)
> I last saw 42
> >>> lastNumber(3)
> I last saw 17
> ##
>
> So for something very simple, using a global will probably be easiest.
>
>
> However, there are other approaches that don't use globals. One that fits
> Python's model well is to use a class instance, since instances can store
> state:
>
> ##
> >>> class LastNumber:
> ... def __init__(self):
> ... self.n = None
> ... def getAndSet(self, x):
> ... value = self.n
> ... self.n = x
> ... return value
> ...
> >>> last = LastNumber()
> >>> last.getAndSet(42)
> >>> last.getAndSet(3)
> 42
> >>> last.getAndSet(7)
> 3
> >>> last.getAndSet(9)
> 7
> ##
>
>
> Does this make sense?  Please feel free to ask questions here.
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] click and line

2005-11-06 Thread Danny Yoo

Hi Shi Mu,

Let's look at click():

##
def click(event):
print event.x, event.y
m1=event.x
n1=event.y
##

By default, variable names in functions are local.  Do you know about
local vs global variables?  The assignments to m1 and n1 won't be
remembered once we come out of the click() function.


It sounds like you want a function-like thing that remembers the very last
event we passed to it before.  One way to do this is to use globals,
because globals last beyond function calls.

For example:

##
>>> n = None
>>> def lastNumber(x):
... global n
... print "I last saw", n
... n = x
...
>>> lastNumber(42)
I last saw None
>>> lastNumber(17)
I last saw 42
>>> lastNumber(3)
I last saw 17
##

So for something very simple, using a global will probably be easiest.


However, there are other approaches that don't use globals. One that fits
Python's model well is to use a class instance, since instances can store
state:

##
>>> class LastNumber:
... def __init__(self):
... self.n = None
... def getAndSet(self, x):
... value = self.n
... self.n = x
... return value
...
>>> last = LastNumber()
>>> last.getAndSet(42)
>>> last.getAndSet(3)
42
>>> last.getAndSet(7)
3
>>> last.getAndSet(9)
7
##


Does this make sense?  Please feel free to ask questions here.

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


[Tutor] click and line

2005-11-06 Thread Shi Mu
I tried to write the follwoing code to draw lines on the anvas based
on the clicked points but retur the message:
>>> Traceback (most recent call last):
  File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\Python23\test\Q_line.py", line 13, in ?
l5=c.create_line(m1,n1,event.x,event.y,fill='blue',width='50')
NameError: name 'm1' is not defined

The ocde migth be naive,...
from Tkinter import *

root = Tk()

c = Canvas(root, bg='#0e2e0e', height=500, width=1000)

def click(event):
print event.x, event.y
m1=event.x
n1=event.y
frame = c
c.bind('',click)
l5=c.create_line(m1,n1,event.x,event.y,fill='blue',width='50')

c.pack()

root.mainloop()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How I use images in a GUI?

2005-11-06 Thread Nathan Pinno
Title: Message




Liam,
I am using Pygame, but I am still don't know how to use it. I read it, and 
it confused me.

  - Original Message - 
  From: Liam 
  Clarke-Hutchinson 
  To: 'Nathan Pinno' 
  Cc: 'tutor@python.org' 
  Sent: November 6, 2005 3:47 PM
  Subject: RE: [Tutor] How I use images in 
  a GUI?
  
  Depends on your GUI toolkit and 
  widget.
  For instance, in wxPython's  wx.BitmapButton widget, there's a 
  specific method to set the bitmap, and then the 
  underlying C++ code interfaces with the GDI portion of the 
  Win32 API and draws it for you.
   http://www.wxpython.org/docs/api/wx.BitmapButton-class.html
   
  I'm not too sure about Tkinter, but I 
  assume it's the same way. With regards to games, I suggest you check out 
  www.pygame.org, instead of trying to use 
  a GUI framework as it makes basic game development very simple, whereas a 
  GUI framework doesn't. Especially with adding images to shapes on 
  screen.
  Regards, 
  Liam 
  Clarke-Hutchinson| Contact Centre 
  Advisor| Ministry of Economic Development 
  DDI +64 3 962 2639 
  | Fax +64 3 962 6220www.med.govt.nz 
  

-Original Message-From: 
[EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of 
Nathan PinnoSent: Monday, 7 November 2005 11:29 
a.m.To: Tutor Mailing ListSubject: [Tutor] How I use 
images in a GUI?
Hey all,
 
I have a question that I can't figure out, despite reading the help and 
everything else. How do I use an image or images in a Graphic User 
Interface, and link them to parts of my code i.e. a picture of a game piece 
to its value?
 
Thanks in advance,
Nathan Pinno
   
  A new monthly electronic newsletter covering all aspects of MED's work 
  is now available.  Subscribers can choose to receive news from any or all 
  of seven categories, free of charge: Growth and Innovation, Strategic 
  Directions, Energy and Resources, Business News, ICT, Consumer Issues and 
  Tourism.  See http://news.business.govt.nz 
  for more details.
   
   
     
  govt.nz - connecting you to New Zealand 
  central & local government services
  
  
  Any opinions expressed in this message are not necessarily those of the 
  Ministry of Economic Development. This message and any files transmitted with 
  it are confidential and solely for the use of the intended recipient. If you 
  are not the intended recipient or the person responsible for delivery to the 
  intended recipient, be advised that you have received this message in error 
  and that any use is strictly prohibited. Please contact the sender and delete 
  the message and any attachment from your computer. 
  

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


Re: [Tutor] Object instances

2005-11-06 Thread John Fouhy
On 07/11/05, DS <[EMAIL PROTECTED]> wrote:
> So, I can see the error of my ways.  I can also see that this behavior
> gives me an opportunity to globally change a value in all of the object
> instances, if I ever had to do something like that.  I just don't have a
> clue as to why objects were designed this way.
>
> Can anyone point me in the right direction?

The difference is between class objects and class instances.

When you say "class Foo: ...", you are creating a class object.  When
you call a class object, you create an instance of that class.

Let's have a look:

>>> class Foo(object):
...   testList = []
...   print 'Foo class object being created now!'
...   def __init__(self):
... self.testList2 = []
... print 'Foo instance being initialised now!'
...
Foo class object being created now!
>>> Foo


When I hit , the python interpreted executed the class
definition.  This is why it printed out "Foo class object being
created now!".  This is also when it executed "testList = []". 
testList is an attribute of Foo:

>>> Foo.testList
[]
>>> Foo.testList.append(5)
>>> Foo.testList
[5]

On the other hand, the code in Foo.__init__ did not execute.  That
code will only execute when we create an instance of Foo.  So, Foo has
no testList2 attribute, because "self.testList2 = []" only happens in
__init__.

>>> Foo.testList2
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: type object 'Foo' has no attribute 'testList2'

We can create an instance in the usual way, by calling the class object:

>>> f = Foo()
Foo instance being initialised now!

Now, we can get at testList2.

>>> f.testList2
[]

We can also get at testList in the same way --- but testList belongs
to the class, not the instance.

>>> f.testList
[5]
>>> f.testList is f.__class__.testList is Foo.testList
True

I guess the same thing happens with methods --- that there is only one
copy of each method --- but you don't notice, becuase when you call a
method on an instance, it gets passed the instance as the first
parameter.

Hope this helps!

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


Re: [Tutor] Object instances

2005-11-06 Thread Liam Clarke-Hutchinson
Hi DS, 

I'm not sure what language you've dealt with before, but if it was Java or
C++, then you've run into Python's variant of static members.

class X(object):

classMember = True

def __init__(self):
self.instanceMember = True


Does that make it any clearer? As to the why, I'd ask Guido Van Rossum. ;)





-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of DS
Sent: Monday, 7 November 2005 1:20 p.m.
To: tutor@python.org
Subject: [Tutor] Object instances


I had thought I was developing a clue regarding objects in Python, but I ran
across an oddity today that I didn't expect.  It had seemed to me that once
an instance was created, it would have a separate data pool from any other
instance of the same object.  It would share methods, of course, but the
data assigned to it would be totally separate.  After running into peculiar
errors I now see how this is not totally true, but I would like to
understand why not.  I think I'm missing something kind of fundamental here.

The following is my toy example:


In [1]: class test(object):
   ...: testlist = []
   ...:

In [2]: c1 = test()

In [3]: c1.testlist.append(0)

In [4]: c2 = test()

In [5]: c2.testlist
Out[5]: [0]

In this example, I create two instances of the object test, assigned data to
c1.testlist and it shows up in the other instance, c2. 
Typically, I have been assigning values within an object from being passed
in via __init__, but it seemed like it wasn't really necessary for this
particular kind of object.  In my next example, I show the creation of
testlist via an __init__ and all goes as I expected.


In [10]: class test(object):
   : def __init__(self):
   : self.testlist = []
   :

In [11]: c1 = test()

In [12]: c2 = test()

In [13]: c1.testlist.append(0)

In [14]: c2.testlist
Out[14]: []

So, I can see the error of my ways.  I can also see that this behavior gives
me an opportunity to globally change a value in all of the object instances,
if I ever had to do something like that.  I just don't have a clue as to why
objects were designed this way.

Can anyone point me in the right direction?

Thanks

ds




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

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Object instances

2005-11-06 Thread DS
I had thought I was developing a clue regarding objects in Python, but I
ran across an oddity today that I didn't expect.  It had seemed to me
that once an instance was created, it would have a separate data pool
from any other instance of the same object.  It would share methods, of
course, but the data assigned to it would be totally separate.  After
running into peculiar errors I now see how this is not totally true, but
I would like to understand why not.  I think I'm missing something kind
of fundamental here.

The following is my toy example:


In [1]: class test(object):
   ...: testlist = []
   ...:

In [2]: c1 = test()

In [3]: c1.testlist.append(0)

In [4]: c2 = test()

In [5]: c2.testlist
Out[5]: [0]

In this example, I create two instances of the object test, assigned
data to c1.testlist and it shows up in the other instance, c2. 
Typically, I have been assigning values within an object from being
passed in via __init__, but it seemed like it wasn't really necessary
for this particular kind of object.  In my next example, I show the
creation of testlist via an __init__ and all goes as I expected.


In [10]: class test(object):
   : def __init__(self):
   : self.testlist = []
   :

In [11]: c1 = test()

In [12]: c2 = test()

In [13]: c1.testlist.append(0)

In [14]: c2.testlist
Out[14]: []

So, I can see the error of my ways.  I can also see that this behavior
gives me an opportunity to globally change a value in all of the object
instances, if I ever had to do something like that.  I just don't have a
clue as to why objects were designed this way.

Can anyone point me in the right direction?

Thanks

ds




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


Re: [Tutor] How I use images in a GUI?

2005-11-06 Thread Liam Clarke-Hutchinson
Title: Message



Depends on your GUI toolkit and 
widget.
For instance, in wxPython's  wx.BitmapButton widget, there's a 
specific method to set the bitmap, and then the 
underlying C++ code interfaces with the GDI portion of the Win32 
API and draws it for you.
 http://www.wxpython.org/docs/api/wx.BitmapButton-class.html
 
I'm not too sure about Tkinter, but I assume 
it's the same way. With regards to games, I suggest you check out www.pygame.org, instead of trying to use a 
GUI framework as it makes basic game development very simple, whereas a GUI 
framework doesn't. Especially with adding images to shapes on 
screen.
Regards, 
Liam 
Clarke-Hutchinson| Contact Centre 
Advisor| Ministry of Economic Development 
DDI +64 3 962 2639 | 
Fax +64 3 962 6220www.med.govt.nz 

  
  -Original Message-From: 
  [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of 
  Nathan PinnoSent: Monday, 7 November 2005 11:29 
  a.m.To: Tutor Mailing ListSubject: [Tutor] How I use 
  images in a GUI?
  Hey all,
   
  I have a question that I can't figure out, despite reading the help and 
  everything else. How do I use an image or images in a Graphic User Interface, 
  and link them to parts of my code i.e. a picture of a game piece to its 
  value?
   
  Thanks in advance,
  Nathan Pinno
 
A new monthly electronic newsletter covering all aspects of MED's work is 
now available.  Subscribers can choose to receive news from any or all of 
seven categories, free of charge: Growth and Innovation, Strategic Directions, 
Energy and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz 
for more details.
 
 
 

 
govt.nz - connecting you to New 
Zealand central & local government services


Any opinions expressed in this message are not necessarily those of the Ministry 
of Economic Development. This message and any files transmitted with it are 
confidential and solely for the use of the intended recipient. If you are not 
the intended recipient or the person responsible for delivery to the intended 
recipient, be advised that you have received this message in error and that any 
use is strictly prohibited. Please contact the sender and delete the message and 
any attachment from your computer. 






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


Re: [Tutor] Dictionary Error: 'dict' object hasnoattribute '_contains_'

2005-11-06 Thread Alan Gauld
> Oh, about four years ago :-) in Python 2.2
> 
> You really should read the "What's New in Python x.x" docs ;)

:-)

Hmm, I usually skim them but pick up most of my info from this 
list because I rarely upgrade to the latest version right away 
- I only upgraded my XP box. to 2.4 a few weeks ago...

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


[Tutor] How I use images in a GUI?

2005-11-06 Thread Nathan Pinno



Hey all,
 
I have a question that I can't figure out, despite reading the help and 
everything else. How do I use an image or images in a Graphic User Interface, 
and link them to parts of my code i.e. a picture of a game piece to its 
value?
 
Thanks in advance,
Nathan Pinno
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_'

2005-11-06 Thread Alan Gauld
> I used to want that syntax when I started, now I stick to for x in 
> y.keys()

I knew you could do

for item in dictionary:

instead of

for item in dictionary.keys():

But I didn't realise it worked for a single item test too

if item in dictionary

instead of

if dictionary.has_key(item):

While the loop is probably as easy to read either way
the test is much cleaner using 'in'.

Nice.

Alan g.

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


Re: [Tutor] draw lines

2005-11-06 Thread Kent Johnson
Shi Mu wrote:
> I have a list of random points:
> [[x0,y0],[x1,y1],...,[xn,yn]]
> how can I use Tkinter to draw lines to connect them one by one based
> on the order in the list?

You can use a Canvas widget to draw lines. You will probably have to scale your 
coordinates to match the coordinates of the screen.

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] draw lines

2005-11-06 Thread Danny Yoo


On Sun, 6 Nov 2005, Shi Mu wrote:

> I have a list of random points: [[x0,y0],[x1,y1],...,[xn,yn]] how can I
> use Tkinter to draw lines to connect them one by one based on the order
> in the list?

Do you know how to draw a single line in Tkinter?  Have you looked at the
Canvas widget documentation?

http://www.pythonware.com/library/tkinter/introduction/canvas.htm

Next time, you may want to show us what you've done to try to solve the
problem you have.

For the past few questions, I have not been able to get an intuitive sense
of why you're having trouble figuring out things from documentation.  All
I see right now is that you have some new requirement, and then you ask
the Tutor list for help.  It's the step in-between that is a mystery to
me.

Do you just get stuck, or do you try something to figure out what you
don't know, or...?  Do you know where to look for documentation on
subjects like Tkinter?

It's not that we don't like answering your questions, but we want to make
sure you're learning how to find the answers for yourself too.
Otherwise, we end up being a crutch and we do damage to your learning
skills.

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


Re: [Tutor] draw lines

2005-11-06 Thread John Fouhy
On 07/11/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> I have a list of random points:
> [[x0,y0],[x1,y1],...,[xn,yn]]
> how can I use Tkinter to draw lines to connect them one by one based
> on the order in the list?

You need to use a Tkinter.Canvas.

Have a look at Fredrik Lundh's site: http://effbot.org/tkinterbook/canvas.htm

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


[Tutor] draw lines

2005-11-06 Thread Shi Mu
I have a list of random points:
[[x0,y0],[x1,y1],...,[xn,yn]]
how can I use Tkinter to draw lines to connect them one by one based
on the order in the list?
Thanks a lot!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Error: 'dict' object has noattribute '_con tains_'

2005-11-06 Thread Liam Clarke-Hutchinson
I believe around Python 2.2...

I used to want that syntax when I started, now I stick to for x in y.keys()
- The 'explicit > implicit' concept has become important to me; probably
because I do most of my coding after midnight and the "should really be in
bed" mistakes are bad enough, but adding implicitness in any form tends to
increase my time to debug.
I'm learning C at the moment, which has a degree of implicitness that could
bite me; ditto C#.

Regards, 

Liam Clarke-Hutchinson



-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Alan
Gauld
Sent: Monday, 7 November 2005 8:51 a.m.
To: Kent Johnson
Cc: tutor@python.org
Subject: Re: [Tutor] Dictionary Error: 'dict' object has noattribute
'_contains_'


> But you normally shouldn't call this directly, you should write  
> "test" in menu_specials

Now howzabout that! Yet another new trick learnt.
When did 'in' start working with dictionaries?

Alan G.


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

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_'

2005-11-06 Thread Kent Johnson
Alan Gauld wrote:
>> But you normally shouldn't call this directly, you should write
>>  "test" in menu_specials
> 
> 
> Now howzabout that! Yet another new trick learnt.
> When did 'in' start working with dictionaries?

Oh, about four years ago :-) in Python 2.2

You really should read the "What's New in Python x.x" docs ;)

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_'

2005-11-06 Thread Alan Gauld
> But you normally shouldn't call this directly, you should write
>  "test" in menu_specials

Now howzabout that! Yet another new trick learnt.
When did 'in' start working with dictionaries?

Alan G.


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


Re: [Tutor] saving project

2005-11-06 Thread Alan Gauld
>Firstly I am a new programmer on python. I am using Python 2.4.1 
> with IDLE 1.1.1   

Welcome to the tutor list!

> I can't save my poject in my computer. how can I save my projects and 
> in  which format I must save my projects.

Provided you have typed your code into a new editor window - by 
selecting File->New fromthe menus. Then File->Save As... should save 
the programme

You can save the session from the interactive prompt too by doing the 
same thing, but it doesn't really help since there is no way to reload it 
again - I keep meaning to try to write a filter to allow that! 

Basically treat the >>> prompt as a scratch pad for ideas that will be 
thrown away. Anything you want to save has to be typed into a python 
programme file.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] Dictionary Error: 'dict' object has no attribute '_contains_'

2005-11-06 Thread Alan Gauld
> Hi! I'm on the version 2.4, going through Beginning Python (Wrox),  and 
> I'm getting the above error. I'm trying to do this:
>
> menu_specials._contains_("test")
>
> Any ideas on what I'm doing wrong? Thanks!

It looks like you may be reading the wrong book!
Why they would suggest you ever execute that code I have no idea,
using the has_key() method is the normal way to do that.

However, if you really want to call contains() it has two underscores on 
each side.
This is a standard Python idiom for naming functions which you are *not*
expected to call directly. Occasionally you do need to do so but never
as a beginner! Hence why is "Beginning Python" even telling you about them?

The purpose of the  __contains__ () function is to allow you to modify the
behaviour of the has_key() method (which does call __contains__() ) should
you define your own dictionary type, you should not have to call it 
directly.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] overlay

2005-11-06 Thread Chris or Leslie Smith
| From: Shi Mu 
| Is there any sample code to calculate the overlaid area between two
| polygons? 
| Thanks!
| 

The polygon module at ( 
http://www.dezentral.de/warp.html?http://www.dezentral.de/soft/Polygon/ ) was 
found by googling for "polygon module python".  If by "overlay" you mean the 
area in common between two polygons, it can handle this:

###
>>> import Polygon
>>> a=Polygon.Polygon(((0.,0.),(1.,0.),(0.,1.))) #it closes automatically back 
>>> to starting pt
>>> b=Polygon.Polygon(((0.,0.),(1.,0.),(1.,1.)))
>>> c = a & b
>>> Polygon.pointList(c)
[(1.0, 0.0), (0.0, 0.0), (0.5, 0.5)]
>>> c.area()
0.25
>>>
###

Note: the pdf docs did not appear to be included in the download from the page 
cited above; there is a link on the page cited above that downloads it for you.

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


Re: [Tutor] Dictionary Error: 'dict' object has no attribute '_contains_'

2005-11-06 Thread Kent Johnson
Trent Rigsbee wrote:
> Hi! I'm on the version 2.4, going through Beginning Python (Wrox),  and I'm 
> getting the above error. I'm trying to do this:
> 
> menu_specials._contains_("test")
> 
> Any ideas on what I'm doing wrong? Thanks!

The name of the method is __contains__ (note *double* leading and trailing 
underscores). But you normally shouldn't call this directly, you should write
  "test" in menu_specials
instead.

In general the methods and atttributes whose names start and end with double 
underscores are special to the language (in fact they are called 'special 
methods') and they are rarely called by code you write. They are hooks that let 
the author of a class define its behaviour. In this case, the __contains__() 
method is created to define how a dict object tests for membership.

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] interfaces and abstract classes in python

2005-11-06 Thread Kent Johnson
Alex Hunsley wrote:
> Interfaces and abstract classes - I know they don't exist per se in 
> Python. But what are the closest analogues? I've found a few examples, 
> e.g. for an abstract class the following page has a fairly common 
> suggestion:
> 
> http://www.norvig.com/python-iaq.html

Interfaces are generally implicit in Python. For example the docs will 
sometimes talk about 'file-like objects' which are just objects that implement 
the same interface as a file object. 'iterable', 'iterator', 'sequence' and 
'mapping' are similarly defined by convention or by explicit documentation but 
not in the language itself. For example the 'iterator protocol' is defined here:
http://docs.python.org/lib/typeiter.html

To define an abstract method I just raise NotImplementedError in the body of 
the method.

There are a couple of more formalized ways to add support for explicit type 
requirments to the language. This is a little different from what you asked - 
these projects allow a client of an object to specify an interface (or 
protocol) that must be supported by the object.
PyProtocols http://peak.telecommunity.com/PyProtocols.html
Zope Interfaces http://www.zope.org/Wikis/Interfaces/FrontPage

PEP 246 formalizes this notion. It seems to be slated for inclusion in Python 
2.5.
http://www.python.org/peps/pep-0246.html

Kent

-- 
http://www.kentsjohnson.com

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


[Tutor] saving project

2005-11-06 Thread sener
hi everyone,

Firstly I am a new programmer on python. I am using Python 2.4.1 
with IDLE 1.1.1   
I can't save my poject in my computer. how can I save my projects and 
in  which format I must save my projects.

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


[Tutor] Dictionary Error: 'dict' object has no attribute '_contains_'

2005-11-06 Thread Trent Rigsbee
Hi! I'm on the version 2.4, going through Beginning Python (Wrox),  and I'm 
getting the above error. I'm trying to do this:

menu_specials._contains_("test")

Any ideas on what I'm doing wrong? Thanks!


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


Re: [Tutor] interfaces and abstract classes in python

2005-11-06 Thread Alan Gauld
> Interfaces and abstract classes - I know they don't exist per se in 
> Python. 

First you need to define what you mean by the terms.
Every class has an interface - it is the set of messages to which 
it responds.

An Abstract class is one which is not intended to be instantiated.

class AbstractClassError(Exception): pass

class Abstract:
def __init__(self): raise AbstractClassError

> But what are the closest analogues? I've found a few examples, 

Assuming you mean Interface in the Microsoft/Java specific sense 
of the term rather than the simple OOP sense, then an Interface 
class is simply an abstract  class with empty methods.

class InterfaceError(Exception): pass

class Interface(Abstract):
def myMethod(self): pass
def myOther(self): raise InterfaceErrror

Does that do what you want?

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] inside

2005-11-06 Thread Alan Gauld
> just return the "Simple pointInPoly() test..."
> no return from point_inside_polygon(3,10,poly)


if __name__ == '__main__':
   print 'Simple pointInPoly() test...'

   poly = [(-1,-1), (6,-1), (5,6), (0,5)]
   point_inside_polygon(3,10,poly)
-

You need to print it to see it The function returns a value 
which you ignore.

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


Re: [Tutor] color vector

2005-11-06 Thread Kent Johnson
Shi Mu wrote:
> why the following code does not work?

In what way does it not work? 

Kent

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


Re: [Tutor] point and polygon

2005-11-06 Thread Kent Johnson
Shi Mu wrote:
> why the following code report error?

What error does it report? If you show us the error message and the full stack 
trace it will be easier to answer your question.

Kent

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


Re: [Tutor] replacing spaces and tabs before the code

2005-11-06 Thread Kent Johnson
铁石 wrote:
>  I am try to write a code that turn codes to html file

You might be interested in existing solutions. Here is an old list, there are 
probably more now:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/904b11321e07460a/fc9a13cf4baf3b05%23fc9a13cf4baf3b05?sa=X&oi=groupsr&start=1&num=3
Pudge is a new one:
http://pudge.lesscode.org/

> I do it like this,(It is take out from example code form sourceforge):
> 
> re_lead=re.compile(r"[\f\t]")
> re_space=re.compile(r"[ ]{2,}")
> src = re_lead.sub(r" ",src) 
> src = re_lead.sub(r" ",src) 
> 
>   src is the code string!
>   as you can see, I repeat the search many time to replace two or more \t 
> before the code line.
>   but, if somebody use space, some time may be up to 8 or 9 times before a 
> line,it 
> would be stupid to repeat 8 time of search to replace them!
>   It's there a method that can replace  all spaces with " " just at one 
> search 
> action, and pass the single space between words!

re.sub() can take a function (or any callable) as the 'replacement' parameter.  
The function gets a Match object as its argument and returns the replacement 
string. This is very handy when you need to do some processing on the match to 
figure out what the correct replacement string is.

Here is an example that looks at the length of the match and returns a 
corresponding number of   (BTW your example is missing the final semicolon 
- should be ' ')
 >>> import re
 >>> spaceRe = re.compile(r'^( +)')
 >>> def spaceRepl(m):
 ...   num = len(m.group(1))
 ...   return ' '*num
 ...
 >>> spaceRe.sub(spaceRepl, 'def foo():')
'def foo():'

Kent

-- 
http://www.kentsjohnson.com

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


Re: [Tutor] overlay

2005-11-06 Thread Glen Wheeler

  I would do this by clipping the two polygons together, and then 
calculating the area of the resultant polygon.

  You can do that using the Weiler-Atherton polygon clipping algorithm, 
which is rather common.

  Glen

From: "Shi Mu" <[EMAIL PROTECTED]>
> Is there any sample code to calculate the overlaid area between two 
> polygons?
> Thanks!
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] overlay

2005-11-06 Thread Shi Mu
Is there any sample code to calculate the overlaid area between two polygons?
Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fw: point and polygon

2005-11-06 Thread Glen Wheeler

  Missed the rest of the list with this.
  Still sent to Shi however.

From: "Shi Mu" <[EMAIL PROTECTED]>
> why the following code report error?
>
> [..]
>assert pointInPoly(pointA, poly)
>assert not pointInPoly(pointB, poly)

  Assuming your function is correct, the asserts are failing, and python is
 telling you about it.  Asserts exist for many reasons but not for output.
 What you most likely want is:

 if pointInPoly(pointA, poly):
print "pointA in poly"
 else:
print "pointA not in poly"

  With a similar conditional for pointB.

  HTH,
  Glen

 L:Pyt E+++ T-- R+ P+++ D+ G+ F:*band !RL RLA-
W:AF Q+++ AI++ GFX++ SFX-- RN PO--- !Hp Re-- S+ 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inside

2005-11-06 Thread Liam Clarke
This is why -

if __name__ == '__main__':
  print 'Simple pointInPoly() test...'

  poly = [(-1,-1), (6,-1), (5,6), (0,5)]
  point_inside_polygon(3,10,poly)

And you were expecting to see a True/False as to whether or not the
point was inside the polygon right, as point_inside_polygon() returns
True/False...

Try changing it to -

if __name__ == '__main__':
  print 'Simple pointInPoly() test...'

  poly = [(-1,-1), (6,-1), (5,6), (0,5)]
  if point_inside_polygon(3,10,poly):
  print "Point is inside polygon"
  else:
  print "Point is not inside polygon"


On 11/7/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> there is no error message but in the console
> I just see Simple pointInPoly() test...
>
>
> On 11/6/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> > Shi,
> >
> > I've just seen 3 queries from you all along the lines of -
> >
> > why the following code does not work?
> >
> > 
> >
> > If English is not your first language, I can understand you're not
> > going to write us a novel.
> > However, you'll get a better response if you copy and paste the error
> > message (the traceback) that you're getting in the console.
> >
> > Do you know how to copy and paste from the console?
> >
> > A lot of us aren't anywhere we can run your code; if we did, it may
> > work, the error may not be an unhandled exception, just unexpected
> > behaviour, and we have no idea what behaviour you're expecting.
> >
> > So please, in future give us this basic information -
> >
> > If there's an error message - copy and paste the error message
> > If there is no error message - tell us what you expected to happen,
> > and what happened instead.
> >
> > Regards,
> >
> > Liam Clarke
> > On 11/7/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> > > why the following code does not work?
> > >
> > > # determine if a point is inside a given polygon or not
> > > # Polygon is a list of (x,y) pairs.
> > >
> > > def point_inside_polygon(x,y,poly):
> > >
> > > n = len(poly)
> > > inside =False
> > >
> > > p1x,p1y = poly[0]
> > > for i in range(n+1):
> > > p2x,p2y = poly[i % n]
> > > if y > min(p1y,p2y):
> > > if y <= max(p1y,p2y):
> > > if x <= max(p1x,p2x):
> > > if p1y != p2y:
> > > xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
> > > if p1x == p2x or x <= xinters:
> > > inside = not inside
> > > p1x,p1y = p2x,p2y
> > >
> > > return inside
> > >
> > > if __name__ == '__main__':
> > >print 'Simple pointInPoly() test...'
> > >
> > >poly = [(-1,-1), (6,-1), (5,6), (0,5)]
> > >point_inside_polygon(3,10,poly)
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inside

2005-11-06 Thread Shi Mu
there is no error message but in the console
I just see Simple pointInPoly() test...


On 11/6/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Shi,
>
> I've just seen 3 queries from you all along the lines of -
>
> why the following code does not work?
>
> 
>
> If English is not your first language, I can understand you're not
> going to write us a novel.
> However, you'll get a better response if you copy and paste the error
> message (the traceback) that you're getting in the console.
>
> Do you know how to copy and paste from the console?
>
> A lot of us aren't anywhere we can run your code; if we did, it may
> work, the error may not be an unhandled exception, just unexpected
> behaviour, and we have no idea what behaviour you're expecting.
>
> So please, in future give us this basic information -
>
> If there's an error message - copy and paste the error message
> If there is no error message - tell us what you expected to happen,
> and what happened instead.
>
> Regards,
>
> Liam Clarke
> On 11/7/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> > why the following code does not work?
> >
> > # determine if a point is inside a given polygon or not
> > # Polygon is a list of (x,y) pairs.
> >
> > def point_inside_polygon(x,y,poly):
> >
> > n = len(poly)
> > inside =False
> >
> > p1x,p1y = poly[0]
> > for i in range(n+1):
> > p2x,p2y = poly[i % n]
> > if y > min(p1y,p2y):
> > if y <= max(p1y,p2y):
> > if x <= max(p1x,p2x):
> > if p1y != p2y:
> > xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
> > if p1x == p2x or x <= xinters:
> > inside = not inside
> > p1x,p1y = p2x,p2y
> >
> > return inside
> >
> > if __name__ == '__main__':
> >print 'Simple pointInPoly() test...'
> >
> >poly = [(-1,-1), (6,-1), (5,6), (0,5)]
> >point_inside_polygon(3,10,poly)
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inside

2005-11-06 Thread Liam Clarke
Shi,

I've just seen 3 queries from you all along the lines of -

why the following code does not work?



If English is not your first language, I can understand you're not
going to write us a novel.
However, you'll get a better response if you copy and paste the error
message (the traceback) that you're getting in the console.

Do you know how to copy and paste from the console?

A lot of us aren't anywhere we can run your code; if we did, it may
work, the error may not be an unhandled exception, just unexpected
behaviour, and we have no idea what behaviour you're expecting.

So please, in future give us this basic information -

If there's an error message - copy and paste the error message
If there is no error message - tell us what you expected to happen,
and what happened instead.

Regards,

Liam Clarke
On 11/7/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> why the following code does not work?
>
> # determine if a point is inside a given polygon or not
> # Polygon is a list of (x,y) pairs.
>
> def point_inside_polygon(x,y,poly):
>
> n = len(poly)
> inside =False
>
> p1x,p1y = poly[0]
> for i in range(n+1):
> p2x,p2y = poly[i % n]
> if y > min(p1y,p2y):
> if y <= max(p1y,p2y):
> if x <= max(p1x,p2x):
> if p1y != p2y:
> xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
> if p1x == p2x or x <= xinters:
> inside = not inside
> p1x,p1y = p2x,p2y
>
> return inside
>
> if __name__ == '__main__':
>print 'Simple pointInPoly() test...'
>
>poly = [(-1,-1), (6,-1), (5,6), (0,5)]
>point_inside_polygon(3,10,poly)
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] interfaces and abstract classes in python

2005-11-06 Thread Alex Hunsley
Interfaces and abstract classes - I know they don't exist per se in 
Python. But what are the closest analogues? I've found a few examples, 
e.g. for an abstract class the following page has a fairly common 
suggestion:

http://www.norvig.com/python-iaq.html

thanks!
alex

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


Re: [Tutor] inside

2005-11-06 Thread Shi Mu
just return the
"Simple pointInPoly() test..."
no return from point_inside_polygon(3,10,poly)

On 11/6/05, Glen Wheeler <[EMAIL PROTECTED]> wrote:
> > why the following code does not work?
> > [snip script]
>
>  Give us an error message, please.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inside

2005-11-06 Thread Glen Wheeler
> why the following code does not work?
> [snip script]

  Give us an error message, please.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] color vector

2005-11-06 Thread Shi Mu
why the following code does not work?

"""
Tkinter Color Vector Objects

Just the bare minimum to create re-sizable
and re-usable color icons in tkinter.
"""

import Tkinter as Tk
import math
""" Get points for a unit regular-polygon with n sides. """
def getregpoly(sides):
points = []
ang = 2*math.pi / sides
for i in range(sides):
deg = (i+.5)*ang
points.append(math.sin(deg)/2.0+.5)
points.append(math.cos(deg)/2.0+.5)
return points

def scale(points, scale):
return [x*scale for x in points]

def move(points, x, y):
xy = [x,y]*(len(points)//2)
return [xy+coord for xy, coord in zip(xy,points)]

def translate(obj, x, y, zoom):
p = scale(obj.points, obj.size)
p = move(p, obj.x, obj.y)
p = scale(p, zoom)
return move(p, x, y)

def draw(obj, c, x=0 ,y=0, zoom=1):
p = translate(obj, x, y, zoom)
if obj.obj=='line':
c.create_line( p, fill=obj.fill, width=obj.width, arrow=obj.arrow)
elif obj.obj=='rectangle':
c.create_line( p, fill=obj.fill, outline=obj.outline,width=obj.width)
elif obj.obj=='polygon':
c.create_polygon( p, fill=obj.fill,
outline=obj.outline,width=obj.width,smooth=obj.smooth)
elif obj.obj=='text':
size = int(obj.size*zoom)
font = (obj.font,size,obj.style)
c.create_text(p, text=obj.text, font=font, fill=obj.fill)
elif obj.obj=='oval':
c.create_oval( p, fill=obj.fill, outline=obj.outline,width=obj.width )
elif obj.obj=='arc':
c.create_arc( p, start=obj.start,
extent=obj.extent,style=obj.style, fill=obj.fill,outline=obj.outline,
width=obj.width)

class Shape(object):
size = 1
x = y = 0
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __call__(self, *args, **kwds):
for key in self.__dict__:
if key not in kwds:
kwds[key] = self.__dict__[key]
return self.__class__(*args, **kwds)

def draw(self, c, x=0, y=0, scale=1.0):
draw(self, c, x, y, scale)

class Group(list):
obj = 'group'
def __init__(self, *args, **kwds):
self[:] = args
self.__dict__.update(kwds)
def __call__(self, *args, **kwds):
args = self[:]+list(args)
for key in self.__dict__:
if key not in kwds:# make copies
kwds[key] = self.__dict__[key]()
return self.__class__(*args, **kwds)
def draw(self, c, x=0, y=0, scale=1.0):
for item in self:
item.draw(c, x, y, scale)
for key in self.__dict__:
self.__dict__[key].draw(c, x, y, scale)

# base shapes.
text = Shape( obj='text', text='', fill='black', width=0,font='',
style='', points=[0,0] )
line = Shape( obj='line', arrow='none', fill='black',smooth='false',
width=1, points=[0,0,1,0])
rectangle = Shape( obj='rectangle', fill='', outline='black',width=1,
points=[0,0,1,.5])
polygon = Shape( obj='polygon', fill='grey', outline='',width=0,
points=[0,0], smooth='false' )
oval = Shape( obj='oval', fill='grey', outline='',width=0, points=[0,0,1,.75] )
arc = Shape( obj='arc', fill='grey', outline='', width=0,style='arc',
start='0', extent='90',points=[0,0,1,1])

# shape variations
chord = arc(style='chord')
pie = arc(style='pieslice')
circle = oval(points=[0,0,1,1])
square = rectangle(points=[0,0,1,1])
triangle = polygon( points=getregpoly(3))
octagon = polygon( points=getregpoly(8))

# CAUTION ICON
caution = Group(
triangle(x=6, y=5, size=75),
triangle(size=75, fill='yellow'),
txt = text( text='!',
x=38, y=32, size=30,
font='times', style='bold') )

# ERROR ICON
circlepart = chord( x=15, y=15, size=25, fill='red',
start='140', extent='155' )
error = Group(
octagon(x=6, y=5, size=56),
octagon(size=56, fill='red'),
circle(x=9, y=9, size=37, fill='white'),
circlepart(),
circlepart(start='320') )

# QUESTION & INFO ICONS
bubbletip = polygon(points=[34,42,60,56,50,38])
question = Group(
bubbletip(x=6, y=5),
oval(x=6, y=5, size=60),
bubbletip(fill='lightblue'),
oval(size=60, fill='lightblue'),
txt = text( text='?',
x=31, y=22, size=28,
font='times', style='bold' ) )
info = question()
info.txt.text = 'i'

if __name__ == '__main__':
root = Tk.Tk()
root.title('Resizable Shapes')
c = Tk.Canvas(root)

caution.draw(c,40,20,.5)
error.draw(c,120,20,1)
question.draw(c,210,20,2)
info.draw(c,50,100)

logo = caution() # get a copy
logo.txt = text( text='&', fill='#00bb44',
x=39, y=34, size=30 )
logo.draw(c,135,110,1.3)

message = text( text="What's Your Size?",
size=15, fill='white' )
Group( message( x=1, y=1, fill='grey30'),
message() ).draw(c,190,235,2)

line( width=3, fill='darkgrey', arrow='both').draw(c,20,205,336)

c.pack()
root.mainloop()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] inside

2005-11-06 Thread Shi Mu
why the following code does not work?

# determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs.

def point_inside_polygon(x,y,poly):

n = len(poly)
inside =False

p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y

return inside

if __name__ == '__main__':
   print 'Simple pointInPoly() test...'

   poly = [(-1,-1), (6,-1), (5,6), (0,5)]
   point_inside_polygon(3,10,poly)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] point and polygon

2005-11-06 Thread Shi Mu
why the following code report error?
"""
Is given point in polygon?
"""


def pointInPoly(point, pointsList):
"Return True if point is contained in polygon (defined by
given list of points.)"

assert len(pointsList) >= 3, 'Not enough points to define a
polygon (I require 3 or more.)'
assert len(point) >= 2, 'Not enough dimensions to define a
point(I require 2 or more.)'

# If given values are ints, code will fail subtly. Force them to floats.
x,y = float(point[0]), float(point[1])
xp = [float(p[0]) for p in pointsList]
yp = [float(p[1]) for p in pointsList]

# Initialize loop
c=False
i=0
npol = len(pointsList)
j=npol-1

while i < npol:
if yp[i]<=y) and (yhttp://mail.python.org/mailman/listinfo/tutor


[Tutor] replacing spaces and tabs before the code

2005-11-06 Thread 铁石
 I am try to write a code that turn codes to html file
I do it like this,(It is take out from example code form sourceforge):

re_lead=re.compile(r"[\f\t]")
re_space=re.compile(r"[ ]{2,}")
src = re_lead.sub(r" ",src) 
src = re_lead.sub(r" ",src) 

  src is the code string!
  as you can see, I repeat the search many time to replace two or more \t 
before the code line.
  but, if somebody use space, some time may be up to 8 or 9 times before a 
line,it 
would be stupid to repeat 8 time of search to replace them!
  It's there a method that can replace  all spaces with " " just at one 
search 
action, and pass the single space between words!
  I am new to re module,please help! thanks! 

[EMAIL PROTECTED]
  2005-11-06

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


Re: [Tutor] Class attributes not overriding parameters

2005-11-06 Thread Andreas Kostyrka
Am Samstag, den 05.11.2005, 22:30 +0100 schrieb Jan Eden:
> Hi,
> 
> I use the following construction to make sure the data attribute site_id is 
> set only once for each object:
> 
> def GetSiteID(self):
> return self._site_id
> 
> def SetSiteID(self, value):
> if not (hasattr(self, '_site_id') and self._site_id): self._site_id = 
> value
> 
> site_id = property(GetSiteID, SetSiteID)
> 
> site_id is supposed to be set either through a parameter, derived from the 
> server name (the default case) or via a class attribute:
> 
> class SiteList(Lists):
> site_id = 1
> 
> The latter case does not work: the site_id is still derived from the server 
> name for objects of class SiteList. Why is that? How can I make Python check 
> the superclasses for a class attribute before applying the SiteMode() method?

The basic misunderstanding is how it all works :)

class X:
dict_definition

Basically, Python just collects all that definitions into a dictionary,
and it passes it into the type constructor. Using metaclasses one can
actually manipulate this dictionary.

class X:
a = 1
def b(self):
print self.a

x=X()
X.__dict__['b'] # function
X.b # unbound method
x.b # bound method

x.b() # print 1
x.a = 100 # e.g. self.a = self.a + 99
x.b() # print 100
print X.a # print 1
print x.a # print 100

So basically, one of the mechanisms of Python is to look for attributes
(like self.a) first in self, and then in all the class dictionaries.

Back to your example:
class SiteList(Lists):
site_id = 1

you can basically do two things: (both solutions untested)

Use the internal variable name:

class SiteList(Lists):
_site_id = 1 

This way the hasattr method will find a _site_id attribute.

Or use a metaclass, which would then result in something like this

class MyMeta(type):
def __init__(cls, name, bases, dict):
super(MyMeta, cls).__init__(name, bases, dict)
if cls.__dict__.has_key("site_id"):
cls._site_id = cls.site_id
def getSite(self):
return self._site_id
def setSite(self, val):
if not (hasattr(self, '_site_id') and self._site_id):
self._site_id = val
else:
raise TypeError("site_id already set")

cls.site_id = property(getSite, setSite)

class Base(object):
__metaclass__ = MyMeta

class Test(Base):
site_id = 100

t = Base()
t2 = Test()
t.site_id = "Baseid"
print t.site_id
try:
t.site_id = "Baseid"
assert None == "Something went really wrong."
except TypeError:
pass
print t2.site_id

t2.site_id = 101

Andreas


signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class attributes not overriding parameters

2005-11-06 Thread Jan Eden
Hi Liam,

Liam Clarke wrote on 06.11.2005:

>Hi Jan,
>
>Won't this
>
>site_id = property(GetSiteID, SetSiteID)
>
>and this
>
>site_id = 1
>
>collide?
>

Yup. After writing my message, I thought about it again: the property function 
gets never executed when I use the class attribute.

So I changed the setup to this:

class Base:
def GetSiteID(self):
return self._site_id

def SetSiteID(self, value):
if not (hasattr(self, '_site_id') and self._site_id): self._site_id = 
value

site_id = property(GetSiteID, SetSiteID)

class Lists(Base):
...

class SiteList(Lists, Data.Lists):
_site_id = 1

which works just as expected. Thanks for yor help!

- Jan
-- 
A core dump is your computer's way of saying "Here's what's on my mind, what's 
on yours?"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor