Re: [Tutor] Python's OOP-Inheritance make me confuse.

2013-01-19 Thread Dave Angel

On 01/19/2013 02:08 AM, Moore John wrote:

Hi, I am new to Python language.
I have only 10 days experience on it.
When I start learning there is no difficult, but it make me slow down when
I reach "Object Oriented Concept", especially "Inherited".
Some of my background knowledge about "Inherited is the child class can get
all of characteristic and behaviour of parent class, in other words - data
and methods of parent".
Ok, I am going to show the concept that make me confuse with two programs.
Both of them are getting the same result, so why people are making
different.
---Frist--
class Parent():

 parentdata = 0

 def __init__(self):

 pass

 L


Is there a reason that you doublespaced all the code?  It makes it hard 
to see much at a time on the screen.  Or is that a consequence of 
composing the mail as html (also a bad idea here, for several reasons).


First, by omitting the derivation from object, you've made Parent an old 
style class.  Change it to:

class Parent(object):

In version 3.*  Python has only new-style classes, and the change would 
be unnecessary.  But you're using version 2.x


After comparison, I see the only difference was the call to 
Parent.__init__().  That makes no difference, since the called function 
does nothing.  So of course the two files produce the same results.


The real question is what you expected either of them to do.  You have 
no instance data in either class, so the only thing you're "sharing" is 
the methods.  In other words, if you created ten instances of Chld, 
they'd all be identical


To use instance data, you need to use the "self" namespace.  So if the 
Parent class wants instance data called pdata, you'd do something like 
this inside the __init__() method.


 self.pdata = 42

Now, that data will be accessible in the child methods, by doing 
something like

  temp = self.pdata
  .do something with temp




---
And also guide me, how to use "Super()" method for instance of
"Parent.__init__(self)
Somebody used, Super method ih there and some are doing as my way.
I am not clearly these two different.
In these two program - I am not using "__init__" as constructor.
If I am going to use "__init__" as to add data into the class's
data(childdata, parentdata), how do I insert parameter in
"Parent.__init__(self)" and both of their
"def __init__(self):" method.
Thanks



Parameters are done the same in __init__() method as in any other one. 
If you want to take 3 arguments, you might do something as simple as


def __init__(self, arg1, arg2, arg3):
self.data1 = arg1
self.data2 = arg2
self.data3 = arg3

Naturally, you'd pick better names.  Anyway, then you can create an 
instance by doing:


my_object = Parent(value1, value2, value3)

Now you have the beginnings of a useful class.  Each instance stores 
data which can be specified when the instance is created, and modified 
later.


Worry about inheritance after you see what a class is used for to begin 
with.  I think you should play with some realistic classes for a while, 
not just read about them.





--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Struggling with logic .....

2013-01-19 Thread Barry Drake
Hi there   Some months ago I decided to have a crack at Python. I 
set myself the task of coding the 'Mastermind' game and got into great 
problems where the random generated number contained duplicated digits.  
I recently decided to get back to it as I have volunteered to introduce 
the older kids at the local junior school to programming i initially 
using 'Scratch' and then touching on Python.


I found some Mastermind example coding on the internet and took a look.  
I'm playing with the attached:


It seemed to work OK so I re-wrote the input code to be (IMO) more 
logical, and added more text to make it obvious what is happening. Then 
I noticed it doesn't get the scoring right when there are duplicate 
digits!  I'm no expert, so I wonder if you guys can explain in simple 
terms what is happening.  I have to say I feel a bit stupid here.  Below 
is one of the 'mistakes':

$ python mastermind_2.py
I have chosen a random four digit number.  You have to guess what it is.
Give me your guess at the four digit number . Enter four digits 
between 1 and 6: 1234

line is:  ['1', '2', '3', '4']   Length:  4
Random Code:  (3, 4, 2, 3)
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: -1  - you have an incorrect number

I have chosen a random four digit number.  You have to guess what it is.
Give me your guess at the four digit number . Enter four digits 
between 1 and 6: 4215

line is:  ['4', '2', '1', '5']   Length:  4
Random Code:  (3, 4, 2, 3)
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: -1  - you have an incorrect number
Result: -1  - you have an incorrect number


-- Barry Drake is a member of the the Ubuntu Advertising team. 
http://ubuntu.com/


import random

# generate random code
code = (random.randrange(1, 6), random.randrange(1, 6),
random.randrange(1, 6), random.randrange(1, 6))

line= ['','','','']# line from user
cc  = []# code count
cl  = []# line count
matched= 0# number of matched items
result  = [-1, -1, -1, -1]  # result

user_own= False
max_attempts= 10# XXX How to define a constant variable?
attempts= 0

while not user_own and attempts < max_attempts:
#line = raw_input(str(attempts + 1) + " You : ").strip().split(" ")  #  originally
# Barry
print "I have chosen a random four digit number.  You have to guess what it is."
input_str = str(input("Give me your guess at the four digit number . Enter four digits between 1 and 6: "))
for i in range(len(input_str)):
line[i] = input_str[i]
print "line is: ", line, "  Length: ", len(line) # debug hint
print "Random Code: ", code # for debugging only
# /Barry

if input_str == "":
# cheat code for debugging
print "Random Code: ", code

if len(line) != 4:
# won't be considered an attempt
   print "Please enter only 4 digits "
   continue

# convert list members in integer
line = [int(l) for l in line]

# TODO check for color in range 1 to 6

# game has 6 colors
cc = [0, 0, 0, 0, 0, 0]
cl = [0, 0, 0, 0, 0, 0]
matched = 0
for i in range(len(line)):
if line[i] == code[i]:
# matched guess
matched += 1
else:
cc[code[i] - 1] += 1
cl[line[i] - 1] += 1

if matched == 4:
user_own = True
continue

# user is not own, evaluate user guesses
i  = 0
result = [-1, -1, -1, -1]
while i < matched:
# color matched along with position
result[i] =  1
i += 1

ri = i
for i in range(len(cc)):
x = min(cc[i], cl[i])
for i in range(x):
# color matched, position incorrect
result[ri] =  0
ri += 1
if ri == 4:
break;

# XXX Note comma at the end to disable newline
# print "Result:",
for i in result:
print "Result:",  i,
if (i == 1):
print " - you have a correct number in a correct position"
if (i == 0):
print " - you have a correct number in an incorrect position"
if (i == -1):
print " - you have an incorrect number"
attempts += 1
print

if user_own:
print "Congratulations - you have WON!!!"
else:
print "Sorry, YOU LOST!!!"
print "Random Code was:", code
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently

2013-01-19 Thread Albert-Jan Roskam


> On Thu, Jan 17, 2013 at 10:33 AM, Albert-Jan Roskam  
> wrote:
>> 
>>  The goal is to load the C libraries (dll, so, dylib, etc) that my program
>>  needs.
>> 
>>  Anyway, I looked up your two suggestions about library_dirs and
>>  runtime_library_dirs. What is meant by "at link time"?
> 
> library_dirs adds search paths for the linker (e.g. ld) for finding
> shared libraries (.so) and static libraries (.a archives of
> relocatable object files).
> 
> Linking to a shared library is handled by the runtime loader/linker
> (e.g. /lib/ld-linux.so.2). For Linux, ld.so searches the
> system-defined directories (/lib, /usr/lib, and those set by
> /etc/ld.so.conf), which are cached in /etc/ld.so.cache (created by
> ldconfig). This is where distutils runtime_library_dirs comes into
> play. For ELF it configures an embedded RPATH, which the loader
> searches before the system directories. You can also convert the RPATH
> to a RUNPATH, which can be overridden by LD_LIBRARY_PATH.

Thank you! I am getting a whole lot wiser wrt Linux. I checked 'man ld' and 
'man ldconfig'.
Especially the ld command is pretty extensive. The Rpath/Runpath solution seems 
nice in that
no wrapper is needed (contrary to when one uses LD_LIBRARY_PATH). But is 
Windows the only
exception in the way that libraries are dealt with? Or do DLLs also have a 
dynamic area?

 
>>  Does this mean that the ELF header of the library itself is modified
> 
> readelf -d shows the .dynamic section (including strings from
> .dynstr), which you can use to verify the RPATH/RUNPATH. chrpath lets
> you change (but not add) an RPATH, up to its existing length. It also
> lets you convert an RPATH to a RUNPATH. patchELF can add or extend an
> RPATH/RUNPATH.
> 
> http://nixos.org/patchelf.html
> 
>>  The libraries I am using are copyrighted (one can freely use them, but
>>  no reverse engineering, disentangling, etc). I am not sure whether
>>  adding an rpath will be copyright infringement. Logically, I'd say no,
>>  but I doubt whether logic applies in legal stuff.
> 
> It should be OK for internal administration. You'd have to ask a legal
> expert about distribution.

Yes, that would indeed be interesting to know. Unfortuntately, unlike 
developers, these folks are hard to get in touch with.
Maybe theyŕe also a rare species. I think I'ĺl have to follow conservative 
approach here and not patch the ELF.

> If you stick with LD_LIBRARY_PATH, etc, keep in mind it has to be set
> before the process starts, typically in a wrapper script. On Windows,
> however, you can modify PATH at runtime.

So if, at runtime, I do something evil like del os.environ['PATH'] in Windows 
this actually deletes/propagates to my path?? Unlike other OS where os.environ 
is 'just' a dict that contains the paths, that once loaded, cannot be modified 
(well you can modify them, but the OS won know about the changes).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Struggling with logic .....

2013-01-19 Thread Alan Gauld

On 19/01/13 11:14, Barry Drake wrote:


I noticed it doesn't get the scoring right when there are duplicate
digits!


You haven't given an example with duplicate digits so I'll need
to take your word for it!


line is:  ['1', '2', '3', '4']   Length:  4
Random Code:  (3, 4, 2, 3)
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: -1  - you have an incorrect number


Looks good to me


line is:  ['4', '2', '1', '5']   Length:  4
Random Code:  (3, 4, 2, 3)
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: -1  - you have an incorrect number
Result: -1  - you have an incorrect number


Same here. Sooo... Some comments on the code.

##
> import random

> # generate random code
> code = (random.randrange(1, 6), random.randrange(1, 6),
>random.randrange(1, 6), random.randrange(1, 6))
>
> line= ['','','','']# line from user

You probably don't need this although it does no harm

> cc  = []# code count
> cl  = []# line count

Not sure why you need a list for these

> matched= 0# number of matched items
> result  = [-1, -1, -1, -1]  # result

> user_own= False
> max_attempts= 10# XXX How to define a constant variable?

Yes, although convention puts constants in uppercase so:

MAX_ATTEMPTS = 10

It just makes the intention clear. This is not supposed to be changed by 
the program.


> attempts= 0
>
> while not user_own and attempts < max_attempts:
>print "I have chosen a random four digit number.  You have to
>guess what it is."
>input_str = str(input("Give me your guess at the four digit number
> . Enter four digits between 1 and 6: "))
>for i in range(len(input_str)):
> line[i] = input_str[i]

Probably easier to just use list(), maybe with a length check too:

if len(input_str) == 4:
   line = list(input_str)
else:
   # print an error message
   continue

>print "line is: ", line, "  Length: ", len(line) # debug hint

Catch the error don't just display it...

>if len(line) != 4:
># won't be considered an attempt
>   print "Please enter only 4 digits "
>   continue

I'd do this earlier, see above


># convert list members in integer
> line = [int(l) for l in line]

You could do this in the conversion above which becomes:

if len(input_str) == 4:
   line = [int(d) for d in list(input_str)]
else:
   # print an error message
   continue

># TODO check for color in range 1 to 6
>
># game has 6 colors
>cc = [0, 0, 0, 0, 0, 0]
>cl = [0, 0, 0, 0, 0, 0]

This just overwrote the initialisation at the top rendering it irrelevant.

And where do the colors fit in? Your output only used numbers- no 
reference to colors so while debugging get rid of the irrelevant 
stuff... it only distracts.


 >   matched = 0
 >   for i in range(len(line)):
 >   if line[i] == code[i]:
 >   # matched guess
 >   matched += 1
 >   else:
 >   cc[code[i] - 1] += 1
 >   cl[line[i] - 1] += 1

I don't understand what this else clause is doing

>if matched == 4:
>user_own = True
>continue
>
># user is not own, evaluate user guesses
>i  = 0
>result = [-1, -1, -1, -1]

again you are overwriting the initialised value so its pointless doing 
the original initialisation.


>while i < matched:
># color matched along with position
>result[i] =  1
>i += 1
>
>ri = i
>for i in range(len(cc)):
>x = min(cc[i], cl[i])

OK, at this point I give up, this is way too complicated for what you 
are doing.


Consider using sets.
If you create your line as a set of tuples (value,position)
and the same for your input.

The intersect of the two sets is your correct value and position.

Remove these items from both sets and store as the 'matched' set.

For each item in the remaining input set see if there is a corresponding 
value in the line set, if so, remove it from both

and store in the 'nearly' set.

Now report how many items in matched and nearly.

Example:

1225 -> lineset = {(1,0),(2,1),(2,2),(5,3)}

1122 -> inset = {(1,0),(1,1),(2,2),(2,3)}

intersect = {(1,0),(2.2)}  -> matchset

remainder now:

lineset = {(2,1),(5,3)}
inset = {(1,1),(2,3)}

The first inset item does not match any value in linest.
The second inset item matches the value of first item in
lineset so add it to nearlyset:

nearlyset = {(2,3)}

So the final result is:

matchset = {(1,0),(2.2)}  -> len = 2
nearlyset = {2,3) -> len = 1

So result is 2 perfect matches and 1 in wrong position.

Most of this can be done using the python set operations/methods...

I think you'll find it easier...

--
Alan G
Author of the Learn to Program web site
http://www

Re: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently

2013-01-19 Thread Alan Gauld

On 19/01/13 12:24, Albert-Jan Roskam wrote:


Thank you! I am getting a whole lot wiser wrt Linux. I checked 'man ld' and 
'man ldconfig'.
Especially the ld command is pretty extensive. The Rpath/Runpath solution seems 
nice in that
no wrapper is needed (contrary to when one uses LD_LIBRARY_PATH). But is 
Windows the only
exception in the way that libraries are dealt with? Or do DLLs also have a 
dynamic area?


Every OS is different in how it builds executables and links to 
libraries. DOS is different to Windows and Unix. VMS is different again. 
IBM OS/390 is different again. And other OS like Vxworks, and OS/9 are 
similar to *nix but not quite the same. You are really
in the depths of OS internals and need to research every platform on its 
own merits.


The good news is that all unix variants (including Solaris,
BSD, Darwin(MacOS) and linux work very similarly) And Windows is the 
only mainstream exception, at least on the desktop. So unless you are 
writing server software its not too bad.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently

2013-01-19 Thread eryksun
On Fri, Jan 18, 2013 at 4:07 PM, Albert-Jan Roskam  wrote:
>
> Alan said:
>> Support for changing environment variables on the fly is iffy in most
>> languages and is not something I'd ever do lightly.
>
> If you put it that way... yes, I now realize that it could be (and in fact
> is) really annoying if programs do such things. ;-)

As initialized by exec, spawn, or Win32 CreateProcess, a child process
uses a copy of the parent's environment, or a new environment.
Modifying it doesn't carry over to the user's profile, or even the
parent process. That said, there's no portable ANSI C function to
modify the environment. CPython uses putenv; it's in the POSIX spec
and available in Windows. If putenv isn't supported on the platform,
then os.environ is just a dict.

The environment consists of the environ array, with pointers to
combined strings, such as 'foo=bar', that are initially in a
contiguous block of memory. putenv realloc's environ to grow the
number of variables. On a POSIX system the caller is responsible for
allocating the new strings on the heap (not automatic memory on the
stack), and as the name implies the exact string is 'put' into
environ. Windows, in contrast, stores a copy, which is more like POSIX
setenv. Either way, CPython keeps an internal reference so the memory
doesn't get free'd. Another Windows difference is that when putenv is
first called it copies the entire environment block as separately
allocated strings.

You can expand on the simple example below to explore how memory gets
malloc'd and realloc'd outside of the initial environment.

>>> from ctypes import *
>>> env = POINTER(c_char_p).in_dll(CDLL(None), 'environ')
>>> i = 0
>>> while env[i]: i += 1  # the last entry is NULL
...
>>> import os
>>> os.environ['spam'] = 'eggs'
>>> env[i]
'spam=eggs'
>>> print env[i+1]  # new NULL terminator
None

CDLL(None), for accessing global symbols, is particular to POSIX
dlopen. On Windows it works if I use "_environ" out of the active CRT
(e.g. msvcr90.dll, msvcr100.dll, but not msvcrt.dll), which can be
found with find_library('c'):

>>> from ctypes import *
>>> from ctypes.util import find_library
>>> env = POINTER(c_char_p).in_dll(CDLL(find_library('c')), '_environ')
...

On Windows, Python uppercases the keys set via os.environ. Windows
getenv is case insensitive, so the os.py authors opted to normalize to
uppercase so that 'Path' and 'PATH' have the same dict entry. In 2.x
it still calls putenv with mixed-case keys (as long as the values stay
consistent with the dict it doesn't matter), but 3.x only sets
uppercase keys as part of the Unicode encode/decode redesign. Unicode
also lead to changes for non-Windows platforms: the surrogateescape
encoding and os.environb (bytes).

>>>  As an alternative, I used os.chdir to tell the OS where to start
>>>  looking for libraries, but somebody on this list (I forgot who)
>>>  warned me that this could have nasty side effects.

That works for Windows LoadLibrary and OS X dlopen. Linux dlopen
doesn't look in the current directory for a non-path, but you can use
a relative path (e.g. "./libfoo.so"). For a non-path (i.e. no '/' in
the string), ld.so uses the ELF RPATH, LD_LIBRARY_PATH, ELF RUNPATH,
/etc/ld.so.cache, /lib, and /usr/lib.

As to nasty side effects, your process has its own cwd; changing it
doesn't affect the parent (as in the shell). If desired, you can use a
context manager to automatically return to the previous directory,
even (especially) if there's an exception.

> You mean something like a setup.cfg that is read by ConfigParser? The coolest
> would be if it worked out-of-the-box, but this may be the next best thing. I
> want my C libraries and my .py files to live in the same dir (so not in a
> standard location such as /usr/lib, but in site-packages.

If you're loading libraries with ctypes, as mentioned above you can
provide an absolute or relative path. The path for the Python module
is os.path.dirname(__file__). Your libs can be installed there as
package data. If nothing was done to modify the search path, you'll
have to manage dependencies manually. For example, If libspam depends
on libeggs, you can manually load libeggs before loading libspam. For
ELF .so files this requires that libeggs has a correct SONAME tag.
Verify it with readelf -d filename. This will also show dependencies
listed as NEEDED, or you can use ldd to list the dependencies.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently

2013-01-19 Thread eryksun
On Sat, Jan 19, 2013 at 7:24 AM, Albert-Jan Roskam  wrote:
>
> But is Windows the only exception in the way that libraries are dealt with?
> Or do DLLs also have a dynamic area?

DLLs can have an embedded manifest. To solve the DLL Hell problem,
Windows introduced side-by-side assemblies (WinSxS):

Everything you Never Wanted to Know about WinSxS
http://omnicognate.wordpress.com/2009/10/05/winsxs

> So if, at runtime, I do something evil like del os.environ['PATH'] in
> Windows this actually deletes/propagates to my path?? Unlike other OS
> where os.environ is 'just' a dict that contains the paths, that once loaded,
> cannot be modified (well you can modify them, but the OS won know about the
> changes).

That would only unset PATH for your current process, not the parent
process, and not your user profile or system PATH. The latter are set
in the registry (i.e. you need to use _winreg/winreg). If putenv is
supported, os.environ uses it.

That point about Windows PATH is that LoadLibrary evaluates it for
each call. That means you can modify it in Python before calling CDLL.
In Linux, ld.so caches the value of LD_LIBRARY_PATH when the process
starts; it can't be set in Python before calling CDLL. You have to
inherit it from the parent process or explicitly set it in bash/Python
script (e.g. os.fork followed by os.execle with a modified
environment).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of references to object properties

2013-01-19 Thread Jose Amoreira
Thanks for the explanation, Alan
> 
> Is there a good reason to want to do such a thing?

There is a reason, but maybe you won't consider it a good one... 
I was writing a small program to simulate the gravitational dynamics of a 
system of many planets, using scipy's odeint to solve the equations of motion. 
I defined a class, CelestialBody, that describes objects that represent 
planets in my simulation. These objects have three attributes: position, 
velocity and mass (the first two are 3D-vectors; as such, the number of 
attributes is actually 7). The many-body system is represented in the 
simulation by a list of CelestialBody objects.

The dynamical state of the system is represented by a 6N (N being the number 
of planets) component array storing the components of the position and linear 
momentum of each body, and the integration procedures (odeint in this case) 
usually take this array as argument. 

So, in my simulation code I have a list of planets (objects of class 
CelestialBody) because it is a natural way of representing the systems I want 
to simulate, and another list (an numpy.array, actually) storing the positions 
and momenta of each planet, needed for the numerical processing of the 
simulation. But the positions and momenta are already present in the planet 
list, since the objects themselves store that information. Then, the second 
list, even if necessary, is a duplication of things that already are defined 
in the code. I don't like it. It'd be better (no duplication) if it was just a 
list of references to the values stored in the planet objects, I think.

But I see your point.

Thanks again,
Jose Amoreira
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Struggling with logic .....

2013-01-19 Thread Barry Drake

On 19/01/13 14:33, Alan Gauld wrote:

line is:  ['1', '2', '3', '4']   Length: 4
Random Code:  (3, 4, 2, 3)
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: 0  - you have a correct number in an incorrect position
Result: -1  - you have an incorrect number


Looks good to me


line is:  ['4', '2', '1', '5']   Length: 4
Random Code:  (3, 4, 2, 3)


Same here. Sooo... Some comments on the code.


Thanks.  I seem to have misunderstood what the original coder had 
intended.  I suppose the above output is making sense after all.





OK, at this point I give up, this is way too complicated for what you 
are doing.


I guess this is exactly why I have been struggling to understand some of 
the logic in the original code!   I like your idea of sets of tuples for 
input and solution - I'll play around with the idea. Also, I think I 
want to alter the random initialisation - I don't like the way in which 
four separate random digits each with a range of only six are 
generated.  I think generating a four digit number and splitting the 
digits will be a better option.  As you mention, the use of colours in 
the original code is a distraction - I think that is the reason for 
limiting the digits to numbers between 1 and 6 - simply based on the old 
board-game.  There's no other logical reason so I'll do away with that 
concept.


Thanks again for your time.  I'm GOING to learn to code Python!  I used 
to code in C many years ago and never made the jump to C++, but Python 
has much nicer features for a novice.  Incidentally, if I re-code the 
example, should I alter it to Python3 syntax while I'm at it?  Is there 
any good reason to move away from Python2?


Kind regards,Barry.

-- Barry Drake is a member of the the Ubuntu Advertising team. 
http://ubuntu.com/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of references to object properties

2013-01-19 Thread Alan Gauld

On 19/01/13 15:47, Jose Amoreira wrote:


motion. I defined a class, CelestialBody, that describes objects that
represent planets in my simulation. These objects have three attributes:
position, velocity and mass (the first two are 3D-vectors; as such, the
number of attributes is actually 7). The many-body system is represented
in the simulation by a list of CelestialBody objects.


OK, why not hold that list in the CelestialBody class?

Then get the list to either hold a copy of the key values or generate it 
on demand. If the list of values is also in the class definition all the 
descendant types of body can update the class list at the same time as 
updating their own copy. It means duplicating data but it keeps the 
instances in control of the data while making it available (read-only, 
from the class) when needed. The overhead is creating the getter/setter 
methods to update the class list in parallel with the instance data.


Alternatively store it once at class level and create properties of the 
instance that do all access in the class list. That way it looks like 
you are updating the instance but the instance delegates the storage to 
the class list. The instance can store its own  index into the class 
list as advised by the class on creation.


There are ways of doing what you want that keep responsibility in the 
object. The choice will depend on how often you need to vary the 
instance values as opposed to using the class list.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Struggling with logic .....

2013-01-19 Thread Alan Gauld

On 19/01/13 16:50, Barry Drake wrote:


has much nicer features for a novice.  Incidentally, if I re-code the
example, should I alter it to Python3 syntax while I'm at it?  Is there
any good reason to move away from Python2?


Python 3 is the future so getting used to it sooner rather than later is 
a good thing. But functionally, for now, there is no great reason to move.


If I were you, starting out relatively fresh,  I'd probably go Pyton 3 
just to save relearning. But be aware not all 3rd party libraries are 
ported yet...



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-19 Thread Scurvy Scott
[SNIP]

Thank you guys so much, sorry for the delayed response. It's awesome
being able to learn a thing or two from people who know so much about
their craft. I've got the code working the way I envisioned it now and
probably couldn't without y'alls help.

I'm so glad this mailing list exists, thanks again.

Scott
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Traffic Light

2013-01-19 Thread anthonym
Hello All,

I am new to Python and taking a course now.  One of my exercises is to
create a traffic light using tkinter.   The exercise also requires that I
create radio buttons that allow the user to click on the color and the
corresponding light will come on.

I followed some examples in my book to write the code but get some errors
that I don't understand .  Code and error messages below

Thanks,
Tony

from tkinter import *  # Import tkinter

class Trafficlight:
def __init__(self):
window = Tk()# Create a window
window.title("Traffic Light")   # Set a title

# Add three radio buttons to frame1
frame1 = Frame(window)   # Create and add a frame to window
frame1.pack()
self.v1 = IntVar()
self.v2 = IntVar()
rbRed = Radiobutton(frame1, text = "Red", bg = "red",
variable = self.v2,
value = 1,
command = self.processRadiobutton)
rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow",
variable = self.v2, value = 2,
command = self.processRadiobutton)
rbGreen = Radiobutton(frame1, text = "Green", bg = "green",
variable = self.v2, value = 3,
command = self.processRadiobutton)

rbRed.grid(row = 10, column = 1)
rbYellow.grid(row = 10, column = 2)
rbGreen.grid(row = 10, column = 3)

# Add Radio Button process below once I figure that out

# Place canvas in the window

self.canvas = Canvas(window, width = 480, height = 480, bg =
"white")
self.canvas.pack()

# Display a rectangle

def displayRect(self):
self.canvas.create_rectangle(10, 10, 190, tages = "rect")

# Display a Oval for the top light

def displayOval(self):
self.canvas.create_oval(10, 10, 10, 10)

# Display an Oval for the middle light

def displayOval(self):
self.canvas.create_oval(20, 20, 20, 20)

# Display an Oval for the bottom light

def displayOval(self):
self.canvas.create_oval(30, 30, 30, 30)

 # Create an event loop

Trafficlight()



Error messages

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 02:56:36)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>>  RESTART 
>>> 
Traceback (most recent call last):
  File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 57, in

Trafficlight()
  File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 16, in
__init__
command = self.processRadiobutton)
AttributeError: 'Trafficlight' object has no attribute 'processRadiobutton'
>>>  RESTART 
>>> 
Traceback (most recent call last):
  File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 57, in

Trafficlight()
  File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 16, in
__init__
command = self.processRadiobutton)
AttributeError: 'Trafficlight' object has no attribute 'processRadiobutton'
>>> 


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread Alan Gauld

On 19/01/13 20:31, anthonym wrote:


 rbRed = Radiobutton(frame1, text = "Red", bg = "red",
 variable = self.v2,
 value = 1,
 command = self.processRadiobutton)


Here you assign your method to the button


 # Add Radio Button process below once I figure that out


But you haven't defined it, it does not exist.
So python complains.

You need to define something, even just a pass:


 def processRadioButton(self): pass



16, in __init__
 command = self.processRadiobutton)
AttributeError: 'Trafficlight' object has no attribute 'processRadiobutton'



HTH

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread anthonym
Thanks again for the info Alan.  I am still passing the button process
until I can get my rectangle and ovals on the canvass.  The program runs
and produces a window with the radio buttons on top.  I would like them on
the bottom but changes to the row field have no effect.

Anybody have any ideas on why I don't see my shape on the canvass?

Thanks,
Tony

On 1/19/13 1:02 PM, "Alan Gauld"  wrote:

>On 19/01/13 20:31, anthonym wrote:
>
>>  rbRed = Radiobutton(frame1, text = "Red", bg = "red",
>>  variable = self.v2,
>>  value = 1,
>>  command = self.processRadiobutton)
>
>Here you assign your method to the button
>
>>  # Add Radio Button process below once I figure that out
>
>But you haven't defined it, it does not exist.
>So python complains.
>
>You need to define something, even just a pass:
>
>
>  def processRadioButton(self): pass
>
>
>> 16, in __init__
>>  command = self.processRadiobutton)
>> AttributeError: 'Trafficlight' object has no attribute
>>'processRadiobutton'
>
>
>HTH
>
>-- 
>Alan G
>Author of the Learn to Program web site
>http://www.alan-g.me.uk/
>
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of references to object properties

2013-01-19 Thread DoanVietTrungAtGmail
Hi Jose, have you thought about shallow copying?

I am learning Python too, so I can be wrong here. But I have just tried the
idea and it worked for me:

class celestialBody(object):
def __init__(self, m, x, y, z):
self.mass = m
self.pos = [x, y, z]
def __str__(self):
return str(self.mass) + ' and ' + str(self.pos)

earth = celestialBody(1, 0, 0, 0)
jupiter = celestialBody(2, 2, 2, 2)
asteroid = celestialBody(0.1, 1, 1, 1)

planetSystem = [earth, jupiter]

positionVectors = [earth.pos, jupiter.pos]

print "object earth's mass and original position is", earth

# Now we make changes to earth's coordinates one by one
# not by manipulating earth but by manipulating the positionVectors
positionVectors[0][0] = positionVectors[0][0] + 0.01*asteroid.pos[0]
positionVectors[0][1] = positionVectors[0][1] + 0.01*asteroid.pos[1]
positionVectors[0][2] = positionVectors[0][2] + 0.01*asteroid.pos[2]

print "object earth's new position, as seen in positionVectors, is",
positionVectors[0]
print "object earth's mass and new position, as seen in earth object, is",
earth
print "object earth's mass and new position, as seen in planetSystem, is",
planetSystem[0]

>>> == RESTART ==
>>>
object earth's mass and original position is 1 and [0, 0, 0]
object earth's new position, as seen in positionVectors, is [0.01, 0.01,
0.01]
object earth's mass and new position, as seen in earth object, is 1 and
[0.01, 0.01, 0.01]
object earth's mass and new position, as seen in planetSystem, is 1 and
[0.01, 0.01, 0.01]
>>>

As to Alan's ideas below, I don't really understand them.

Trung Doan

On Sun, Jan 20, 2013 at 5:01 AM, Alan Gauld wrote:

> On 19/01/13 15:47, Jose Amoreira wrote:
>
>  motion. I defined a class, CelestialBody, that describes objects that
>> represent planets in my simulation. These objects have three attributes:
>> position, velocity and mass (the first two are 3D-vectors; as such, the
>> number of attributes is actually 7). The many-body system is represented
>> in the simulation by a list of CelestialBody objects.
>>
>
> OK, why not hold that list in the CelestialBody class?
>
> Then get the list to either hold a copy of the key values or generate it
> on demand. If the list of values is also in the class definition all the
> descendant types of body can update the class list at the same time as
> updating their own copy. It means duplicating data but it keeps the
> instances in control of the data while making it available (read-only, from
> the class) when needed. The overhead is creating the getter/setter methods
> to update the class list in parallel with the instance data.
>
> Alternatively store it once at class level and create properties of the
> instance that do all access in the class list. That way it looks like you
> are updating the instance but the instance delegates the storage to the
> class list. The instance can store its own  index into the class list as
> advised by the class on creation.
>
> There are ways of doing what you want that keep responsibility in the
> object. The choice will depend on how often you need to vary the instance
> values as opposed to using the class list.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread Matthew Ngaha
On Sat, Jan 19, 2013 at 10:56 PM, anthonym  wrote:
> Thanks again for the info Alan.  I am still passing the button process
> until I can get my rectangle and ovals on the canvass.  The program runs
> and produces a window with the radio buttons on top.  I would like them on
> the bottom but changes to the row field have no effect.
>
> Anybody have any ideas on why I don't see my shape on the canvass?

i doubt i can help, but it might help if you could paste the section
of the code in relation to what you're explaining and tell us what
it's doing? some people don't use tkinter so its a bit hard to
understand what you're saying.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread anthonym
Sure thing.  Here is the code.  And after that is the box I get with the
radio buttons but no shapes.

from tkinter import *  # Import tkinter

class Trafficlight:
def __init__(self):
window = Tk()# Create a window
window.title("Traffic Light")   # Set a title

# Place canvas in the window

self.canvas = Canvas(window, width = 480, height = 480, bg =
"white")
self.canvas.pack()

# Add three radio buttons to frame1
frame1 = Frame(window)   # Create and add a frame to window
frame1.pack()
self.v1 = IntVar()
self.v2 = IntVar()
rbRed = Radiobutton(frame1, text = "Red", bg = "red",
variable = self.v2,
value = 1,
command = self.processRadiobutton)
rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow",
variable = self.v2, value = 2,
command = self.processRadiobutton)
rbGreen = Radiobutton(frame1, text = "Green", bg = "green",
variable = self.v2, value = 3,
command = self.processRadiobutton)

rbRed.grid(row = 400, column = 1)
rbYellow.grid(row = 400, column = 2)
rbGreen.grid(row = 400, column = 3)

 
 
window.mainloop()# Create an event loop

# Display a rectangle

def displayRect(self):
self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect")

# Display a Oval for the top light

def displayOval(self):
self.canvas.create_oval(10, 10, 10, 10)

# Display an Oval for the middle light

def displayOval(self):
self.canvas.create_oval(20, 20, 20, 20)

# Display an Oval for the bottom light

def displayOval(self):
self.canvas.create_oval(30, 30, 30, 30)



 
 
  

# Add Radio Button process below once I figure that out

def processRadiobutton(self): pass

Trafficlight()

from tkinter import *  # Import tkinter

class Trafficlight:
def __init__(self):
window = Tk()# Create a window
window.title("Traffic Light")   # Set a title

# Place canvas in the window

self.canvas = Canvas(window, width = 480, height = 480, bg =
"white")
self.canvas.pack()

# Add three radio buttons to frame1
frame1 = Frame(window)   # Create and add a frame to window
frame1.pack()
self.v1 = IntVar()
self.v2 = IntVar()
rbRed = Radiobutton(frame1, text = "Red", bg = "red",
variable = self.v2,
value = 1,
command = self.processRadiobutton)
rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow",
variable = self.v2, value = 2,
command = self.processRadiobutton)
rbGreen = Radiobutton(frame1, text = "Green", bg = "green",
variable = self.v2, value = 3,
command = self.processRadiobutton)

rbRed.grid(row = 400, column = 1)
rbYellow.grid(row = 400, column = 2)
rbGreen.grid(row = 400, column = 3)

 
 
window.mainloop()# Create an event loop

# Display a rectangle

def displayRect(self):
self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect")

# Display a Oval for the top light

def displayOval(self):
self.canvas.create_oval(10, 10, 10, 10)

# Display an Oval for the middle light

def displayOval(self):
self.canvas.create_oval(20, 20, 20, 20)

# Display an Oval for the bottom light

def displayOval(self):
self.canvas.create_oval(30, 30, 30, 30)



 
 
  

# Add Radio Button process below once I figure that out

def processRadiobutton(self): pass

Trafficlight()













On 1/19/13 3:14 PM, "Matthew Ngaha"  wrote:

>On Sat, Jan 19, 2013 at 10:56 PM, anthonym  wrote:
>> Thanks again for the info Alan.  I am still passing the button process
>> until I can get my rectangle and ovals on the canvass.  The program runs
>> and produces a window with the radio buttons on top.  I would like them
>>on
>> the bottom but changes to the row field have no effect.
>>
>> Anybody have any ideas on why I don't see my shape on the canvass?
>
>i doubt i can help, but it might help if you could paste the section
>of the code in relation to what you're explaining and tell us what
>it's doing? some people don't use tkinter so its a bit hard to
>understand what you're saying.
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python gmail script for conky

2013-01-19 Thread Polo Heysquierdo
I'm getting the following error on my script for conky.

"Traceback (most recent call last):
  File "/home/troll/.gmail/gmail.py", line 1, in 
import urllib.request
ImportError: No module named request"

code below:

import urllib.request
from xml.etree import ElementTree as etree

# Enter your username and password below within quotes below, in place of
.
# Set up authentication for gmail
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='New mail feed',
  url='https://mail.google.com/',
  user= 'username',
  passwd= 'gmail')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)

gmail = 'https://mail.google.com/gmail/feed/atom'
NS = '{http://purl.org/atom/ns#}'
with urllib.request.urlopen('https://mail.google.com/gmail/feed/atom') as
source:
tree = etree.parse(source)
fullcount = tree.find(NS + 'fullcount').text
print(fullcount + ' new')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread Matthew Ngaha
On Sun, Jan 20, 2013 at 12:05 AM, Matthew Ngaha  wrote:
> On Sat, Jan 19, 2013 at 11:29 PM, anthonym  wrote:
>> Sure thing.  Here is the code.  And after that is the box I get with the
>> radio buttons but no shapes.
>
 i might be way off as im struggling to understand how tkinter works,
 but i noticed a few things which hopefully might help. starting with
you wanting the buttons on the bottom of the window and not at the top
where they are showing.

>> from tkinter import *  # Import tkinter
>>
>> class Trafficlight:
>> def __init__(self):
>> window = Tk()
>> self.canvas = Canvas(window, width = 480, height = 480, bg =
>> "white")
>> self.canvas.pack()
>>
>> # Add three radio buttons to frame1
>> frame1 = Frame(window)
>> frame1.pack()
>>
>> rbRed = Radiobutton(frame1, text = "Red", bg = "red",
>> variable = self.v2,
>> value = 1,
>> command = self.processRadiobutton)
>> rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow",
>> variable = self.v2, value = 2,
>> command = self.processRadiobutton)
>> rbGreen = Radiobutton(frame1, text = "Green", bg = "green",
>> variable = self.v2, value = 3,
>> command = self.processRadiobutton)
>>
>> rbRed.grid(row = 400, column = 1)
>> rbYellow.grid(row = 400, column = 2)
>> rbGreen.grid(row = 400, column = 3)
>>
>
 row = 400 seems a bit odd? do you really have 399 occupied rows? you
 define the canvas with absolute positioning: Canvas(window, width =
 480, height = 480). where you trying to place the buttons with
 absolute positioning also? it seems they are appearing inside the
 frame in which you have put them in so why are you trying to move them
 again? im guessing you would have to reposition the Frame itself. also
 you are not using instance variables(self) for either the frame or the
 buttons, maybe they lose the reference to them once moved outside the
 frame.

 as for your shapes not appearing:
>
>>def displayRect(self):
>>self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect")
>>
>>   # Display a Oval for the top light
>>def displayOval(self):
>> self.canvas.create_oval(10, 10, 10, 10)
>> # Display an Oval for the middle light
>>def displayOval(self):
>> self.canvas.create_oval(20, 20, 20, 20)
>> # Display an Oval for the bottom light
>>def displayOval(self):
>> self.canvas.create_oval(30, 30, 30, 30)
>
 If that is the complete code you showed.. Your buttons are not doing
 anything. they are calling a method that does nothing:
 def processRadiobutton(self):
 pass

 also i dont see anywhere in your code where you are calling any of
 those methods that create the shapes. you have to fix your method that
 your buttons are calling, and have it call the correct method for your
 specific shape.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread Alan Gauld

On 19/01/13 23:29, anthonym wrote:

Sure thing.  Here is the code.  And after that is the box I get with the
radio buttons but no shapes.


It all runs fine for me. I'm not sure what you are expecting but it does 
exactly what I'd expect...


The shapes aren't there because you don't draw them. you have some 
functions that might draw shapes but you never call them. And the 
drawOval function gets overwritten twice, so only the last version 
actually exists. You need to call that function with the params or 
rename it something like drawTopLeftOval(). But frankly the generic 
version is better, just keep it to one and pass the values in.



 # Display a rectangle
 def displayRect(self):
 self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect")

 # Display a Oval for the top light
 def displayOval(self):
 self.canvas.create_oval(10, 10, 10, 10)

 # Display an Oval for the middle light
 def displayOval(self):
 self.canvas.create_oval(20, 20, 20, 20)

 # Display an Oval for the bottom light
 def displayOval(self):
 self.canvas.create_oval(30, 30, 30, 30)


Only the last version is actually available in your program it 
overwrites the earlier versions.



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of references to object properties

2013-01-19 Thread eryksun
On Sat, Jan 19, 2013 at 10:47 AM, Jose Amoreira  wrote:
>
> I defined a class, CelestialBody, that describes objects that
> represent planets in my simulation. These objects have three attributes:
> position, velocity and mass (the first two are 3D-vectors; as such, the
> number of attributes is actually 7). The many-body system is represented in
> the simulation by a list of CelestialBody objects.
>
> The dynamical state of the system is represented by a 6N (N being the number
> of planets) component array storing the components of the position and
> linear momentum of each body, and the integration procedures (odeint in this
> case) usually take this array as argument.


Working with views:

>>> import numpy as np

2 planets:

>>> system_state = np.zeros(12)

Create a view for each planet:

>>> mars, earth = [system_state[6*i:6*(i+1)] for i in range(2)]

Modify the views, which also changes the original array:

>>> mars += 1
>>> earth += 2
>>> system_state
array([ 1.,  1.,  1.,  1.,  1.,  1.,  2.,  2.,  2.,  2.,  2.,  2.])

So you can use a CelestialSystem that has the overall state array and
CelestialBody objects that use a view on the latter. Velocity can be a
property, computed from linear momentum and mass.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of references to object properties

2013-01-19 Thread Oscar Benjamin
On 19 January 2013 15:47, Jose Amoreira  wrote:
> Thanks for the explanation, Alan
>
>> Is there a good reason to want to do such a thing?
>
> There is a reason, but maybe you won't consider it a good one...
>
> I was writing a small program to simulate the gravitational dynamics of a
> system of many planets,

I have many times written code for this kind of problem.

> using scipy's odeint to solve the equations of
> motion.

I haven't checked but I wouldn't automatically trust scipy's odeint to
solve these equations through a significant period of time. A simple
method to indicate (not prove) the accuracy of your program would be
to measure how well energy is conserved over time (assuming that your
equations are Hamiltonian).

> I defined a class, CelestialBody, that describes objects that
> represent planets in my simulation. These objects have three attributes:
> position, velocity and mass (the first two are 3D-vectors; as such, the
> number of attributes is actually 7).

It is useful in this kind of problem to draw a distinction between
parameters and variables. Mass is a parameter. Position and velocity
are variables (they change over time).

> The many-body system is represented in
> the simulation by a list of CelestialBody objects.
>
> The dynamical state of the system is represented by a 6N (N being the number
> of planets) component array storing the components of the position and
> linear momentum of each body, and the integration procedures (odeint in this
> case) usually take this array as argument.
>


I would make a class to represent the system as a whole.

class SystemAsAWhole(object):
def __init__(self):
self.numdimensions = 0
self.subsystems = []

def add_subsystem(self, subsys):
 # Add to the list of systems to consider when evaluating the derivative
self.subsystems.append(subsys)
# Adjust the variable indices in the subsystem
self.subsystems.shift(self.numdimensions)
self.numdimensions += subsys.numdimensions

def f(self, x, t, dxdt):
for sys in self.subsystems:
sys.f(x, t, dxdt)

class SubSystem(object):
def __init__(self):
for n, var in self.VARIABLES:
setattr(self, var, n)
# Called when the subsystem is incorporated into a larger system
# Need to adjust our indices to be part of a larger state vector
def shift(self, N):
for var in self.variables:
setattr(self, var, getattr(self, var) + N)

def f(self, x, t, dxdt):
# Compute and return derivative (subclasses need to implement this)
raise NotImplementedError

And then subclass SubSystem to implement the derivative and describe
the variables/parameters:

class SelestialBody(SubSystem):
VARIABLES = ['x', 'y', 'z', 'vx', 'vy', 'vz']
def __init__(self, mass):
self.mass = mass
def f(self, x, t, dxdt):
dxdt[self.x] = x[self.vx]
dxdt[self.y] = x[self.vy]
dxdt[self.z] = x[self.vz]
ax, ay, az = self.force(x)
dxdt[self.vx] = ax
dxdt[self.vy] = ay
dxdt[self.vz] = az

>
>
> So, in my simulation code I have a list of planets (objects of class
> CelestialBody) because it is a natural way of representing the systems I
> want to simulate, and another list (an numpy.array, actually) storing the
> positions and momenta of each planet, needed for the numerical processing of
> the simulation. But the positions and momenta are already present in the
> planet list, since the objects themselves store that information. Then, the
> second list, even if necessary, is a duplication of things that already are
> defined in the code. I don't like it. It'd be better (no duplication) if it
> was just a list of references to the values stored in the planet objects, I
> think.

If you understand the code above you'll see that each planet instance
has attributes giving the indices of the particular variable into the
state vector. This is much better than storing the values as
attributes in the instances themselves. The position of the Earth is a
property of a state of the system which is in turn part of a
particular trajectory. It should be stored as part of a trajectory not
as a property of the object itself. To access the y velocity of the
Earth from the state vector x you can just use x[earth.vy].


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python gmail script for conky

2013-01-19 Thread Andreas Perstinger

On 20.01.2013 00:27, Polo Heysquierdo wrote:

I'm getting the following error on my script for conky.

"Traceback (most recent call last):
   File "/home/troll/.gmail/gmail.py", line 1, in 
 import urllib.request
ImportError: No module named request"


What's your python version?
(Type "python -V" on the command line or "import sys; sys.version" in 
the interpreter)


Bye, Andreas
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Traffic Light

2013-01-19 Thread ALAN GAULD


That must be what I am missing.  How do I call the functions so I can have
>the shapes appear on the canvas?
>
>AG> the same way you call all the other functions.
>AG> The bit I can't answer is *where* you call them. I'm not sure 
>AG> where in your code you want them. 
>AG> Is it before you press the buttons or is it when you press them?
>
>On 1/19/13 5:02 PM, "Alan Gauld"  wrote:
>
>>The shapes aren't there because you don't draw them. you have some
>>functions that might draw shapes but you never call them. 
>
>>
>>>      # Display a rectangle
>>>      def displayRect(self):
>>>          self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect")
>>>
>>>      # Display a Oval for the top light
>>>      def displayOval(self):
>>>          self.canvas.create_oval(10, 10, 10, 10)
>
>AG> So somewhere you need to write
>AG>
>AG> self.displayRect()
>
>
>AG> and
>AG>
>AG>self.displayOval()
>AG>
>AG>Except you probably want to modify them so you do it with the location:
>AG>
>AG>self.displayOval(10,10,10,10)
>
>-- 
>Alan G
>Author of the Learn to Program web site
>http://www.alan-g.me.uk/
>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor