Re: [Tutor] running multiple versions of python

2013-01-12 Thread Wayne Werner

On Thu, 10 Jan 2013, Fowler, Trent wrote:

I am running Windows 7 and I've installed two versions of python, 3.3 and 2.7. 
Python 3.3 was the first version I installed and I was able to run scripts from 
the desktop (not the command line). I installed python 2.7 so that I could get 
numpy, scipy, and matplotlib down the road, but I found that all the scripts on 
my desktop defaulted to python 2.7. Since I coded in 3.3 this caused some 
issues.

I was able to fix this by right clicking the script icon, browsing programs, 
navigating to the python 3.3 file in my C: drive, and selecting the idle inside 
that directory. But then I found I wasn't able to run those scripts with python 
2.7 using the exact same procedure.

Unfortunately I don't know command-line programming very much at all, and it 
seemed like most of what I've seen online is geared towards that as a solution. 
Ideally I'd like to specify which python I want to run a script from the 
desktop, or possibly while I'm editing the script.


I basically have this same setup. To make things work for me, I do this:

- Go to your Python 2 directory ( probably C:\Python2.7> ) and rename
  python.exe to python2.exe and pythonw.exe to pythonw2.exe

- Make sure that both your Python 2 directory and Python 3 directories are on
  your path. You do this by opening the Start Menu and typing "Path" - then hit
  enter. You should have an environment variable called PATH - if not, create a
  new one. You'll want to make sure that you have the paths to Python 3 and 2
  in there. Assuming you've got C:\Python3.3> and C:\Python2.7>, you'd want to
  have a path that contains C:\Python3.3;C:\Python2.7;

Now if you run a python script from cmd or powershell you should be able to do:

C:\some\path> python2 a_matplot_program.py

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


Re: [Tutor] Adding Binary

2013-01-12 Thread Alan Gauld

On 12/01/13 20:43, Ali Raza Ghasemi wrote:

I am making a program that adds binary numbers together. The program has
to accept two binary values (up to 8 binary digits) and output their
total in binary. The output should not contain any leading zeros.


The first thing to realize is that all numbers in a computer are binary. 
Its the repressentation of them on screen that determines whether they 
are in decimal, hex or binary format. Display is a string function. 
Addition is a numeric function so you are going to have to translate 
between the two. And its probably best if your program separates the two 
concepts.



I have a problem in that I don't know how to limit the number digits to
8 as it accepts however many digits you enter


This is presumably an exercise somewhere since we had an identical 
request earlier.
And I ask the same question, why would you want to restrict the length, 
its a bizarre requirement. But since I assume its part of the problem 
spec I'll ignore that...




to ignore anything other than 8-bit 0s and 1s.


OK, that's an extra wrinkle we didn't have last time but its a valid
thing to check.


Here is my code:


And here is a problem, you seem to have posted in HTML and thats lost 
all the formatting so we don't know how your code looks. Pleae post in 
plain text to the list. Especially because formatting is critical in 
Python... But your first post format is visible ok so I'll use that for 
reference...



def add_binary_numbers(num1, num2):
   while True:
   return num1 + num2
   if len(str(num1)) > 8:
   print("Please enter an 8 bit binary number")
   continue


Because the return ends the function the lines after that are *never* 
executed. You probably want the return at the end of the function after 
doing all the checks.


And you probably don't want the checks inside the function, its better 
to keep a function that adds to just doing addition.


Lets assume you do swap them round the next problem is that str() will 
convert to decimal not binary. So you really want to use bin() there.
And bin will add a '0b' prefix so your len() needs to check for 10 not 8 
characters.


Finally calling continue repeats the loop but since you don't change 
anything - nowhere to enter a new number it just repeats forever.

So a bit of a rethink of the logic needed there.


num1 = int(input('please enter the first 8 bit binary number: '),2)
num2 = int(input('please enter the second 8 bit binary number: '),2)


This is fine except by converting the numbers straight away you miss anb 
opportunity to check the user input. And its always best to validate 
input as soon as possible. So i suggest just read the string and check 
the length there and then. Then after checking convert to int()


That way you don't need the check inside the function.

Finally the int(n,2) won't convert if there are non 1/0 characters in 
the string so you can simply catch an error in int() to ensure you get 
valid 1s and 0s.


>>> int('1213',2)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 2: '1213'

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] Adding Binary

2013-01-12 Thread Dave Angel
On 01/12/2013 03:43 PM, Ali Raza Ghasemi wrote:
> I am making a program that adds binary numbers together. The program has to 
> accept two binary values (up to 8 binary digits) and output their total in 
> binary. The output should not contain any leading zeros.
> I have a problem in that I don't know how to limit the number digits to 8 as 
> it accepts however many digits you enter, I also want the program to ignore 
> anything other than 8-bit 0s and 1s. It is a python version 3.2.3
> Here is my code:
> def add_binary_numbers(num1, num2):
> while True:
> return num1 + num2
> if len(str(num1)) > 8:
> print("Please enter an 8 bit binary number")
> continue
> num1 = int(input('please enter the first 8 bit binary number: '),2)
> num2 = int(input('please enter the second 8 bit binary number: '),2)
> result = add_binary_numbers(num1, num2)
> print('the result is', bin(result)[2:])
>
>
>
> I know this isn't a question but it is something I needed help on. This 
> program isn't a homework or an assignment. Help would be much appreciated.
>
>
>

What did you learn from the other thread I told you about?  Is  Ghadir
Chasemi  ghasemm...@leedslearning.net related to you?  Your email
addresses only differ by a couple of letters.

Your code and his/hers differ only in the ordering and other minor
details, so it'd be an amazing coincidence if it didn't have a common
source.

Why are you still using html/rtf text?  Joel Goldstick pointed out that
it frequently messes up formatting on a text mailing list.  Look above
and see how all the indentation you presumably had is lost when I see it.

Do you realize that in a function, after an unconditional return
statement, no other code "in" the function will execute.  Of course,
without fixing the indentation, nothing is inside the function.

Perhaps you'd find the problem easier if you restate the limit, from 8
digits to a value range.  If num1 is less than zero, or greater than
255, it's not correct.

You do know the user could blow up your program by simply entering
something other than a binary value?   Like  "2'  How is that different
than entering a value out of the range you tell him?  If you need to
catch the one case, you should catch the other.  For that you need
try/catch.

Instead of writing a function that does nothing more complex than a "+"
operator, why not write one that accepts a string from the user, try to
convert it, range check it, catch any exceptions, and loop till a valid
value is encountered.


-- 

DaveA

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


[Tutor] Adding Binary

2013-01-12 Thread Ali Raza Ghasemi
I am making a program that adds binary numbers together. The program has to 
accept two binary values (up to 8 binary digits) and output their total in 
binary. The output should not contain any leading zeros.
I have a problem in that I don't know how to limit the number digits to 8 as it 
accepts however many digits you enter, I also want the program to ignore 
anything other than 8-bit 0s and 1s. It is a python version 3.2.3
Here is my code:
def add_binary_numbers(num1, num2):
while True:
return num1 + num2
if len(str(num1)) > 8:
print("Please enter an 8 bit binary number")
continue
num1 = int(input('please enter the first 8 bit binary number: '),2)
num2 = int(input('please enter the second 8 bit binary number: '),2)
result = add_binary_numbers(num1, num2)
print('the result is', bin(result)[2:])



I know this isn't a question but it is something I needed help on. This program 
isn't a homework or an assignment. Help would be much appreciated.

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


Re: [Tutor] a Pygtk question sort of

2013-01-12 Thread ALAN GAULD
Forwarding to the List

Pleae use ReplyAll for list responses.

 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/



>
> From: richard kappler 
>To: Alan Gauld  
>Sent: Saturday, 12 January 2013, 2:15
>Subject: Re: [Tutor] a Pygtk question sort of
> 
>
>
>
>
>I'm not sure what you mean by "down pretty hard" but this definitely looks 
>like a question for a pocketsphinx forum...
>>
>
>
>CMU Sphinx runs forums that would have been appropriate on Sourceforge, but 
>those are "down hard" eg trying to access them gives a 404 error (this is new, 
>they have never been down before, at least in my experience).  The 
>help/discussion forums at python.org are apparently in the midst of migrating 
>to a new format/software and, while there, are unsearchable and mostly missing 
>for the next few days.
> 
>I want to use this code or code
>>>like it in my bot program, so I don't need the gui, button or any of 
>>>that. I
>>>
>>>need pocketsphinx to work exactly as below, but send the text output
>>>back to the main program or to a different program (chatbot) instead of
>>>the gui. Make sense?
>>>
>>Sadly no.
>>Can you explain exactly how you intend running pocketspinx?
>>What is the main program? A Python script? Or some other external program? 
>>Where does chatbot fit in? Is it just an arbitrary example or is there some 
>>specific symbiosis going on?
>
>
>It's a robot I've been working on for some months. It consists of a laptop 
>interfaced with an Arduino board that reads sensors, sends the data to the 
>laptop for decision making and controls the motors based on commands generated 
>by the "main" bot program on the laptop, written in python (2.73). 
>
>
>Among the many separate programs called by the python program that is the 
>"main" part of the bot, will be pocketsphinx for speech recognition, festival 
>for text to speech, Chatscript for the chatbot, the Arduino which coms through 
>serial and other things still being worked out. The Arduino is coded and 
>communicating quite well with the laptop/python program. Chatscript (via 
>boost) and Festival are working well enough for now. I'm trying to work the 
>pocketsphinx bit now.
>
>
>What pocketsphinx needs to do is convert the user's speech to text and send it 
>to the python program ("main program" think master control) via the gst pipe 
>set up in the script I appended to the original post. Come to think of it my 
>terminology is way off here, as I believe the appended script will ultimately 
>be a class within the bot's python program, so think of it more as a main loop 
>within the python program. In that loop the sensors will be read, the AI will 
>determine priorities based on needs or commands, pocketsphinx will listen and 
>convert speech to text returning the text output to the main loop, where the 
>text will be either matched with a few preset sentences for commands like 
>"move forward," "turn left," etc or, if there are no matches there, the text 
>is sent out to Chatscript (a separate, C++ program) for NLP processing and 
>response, which response will be returned to the python program and sent out 
>to Festival for text to speech response,
 then the loop starts over unless the "end program" command is given, in which 
case the loop is exited and the program terminates.
>
>
>Hopefully better?
>
>
> 
>gui method and the button. The problem is the button controls the vader
>>>(determines begin and end of utterances) as well. Detailed explanation
>>>
>>
Nope, you lost me again...
>
>
>The previously appended code basically does three things: 
>1) it creates a little gui text box with a button.  
>2) it uses gst to receive real time audio from the mic and opens a pipeline to 
>---
>3) send the audio to pocketsphinx speech rec engine for decoding to text
>
>
>How it works: start the program, a gui pops up with a button labeled "speak" 
>and behind the scenes gst and pocketsphinx are started/initialized. The vader 
>(voice activity detector), controlled by the button method, determines the 
>beginning and endpoint of an "utterance" (think sentence). So, once the 
>program/script is started and everything up and running, when you push the 
>"speak" button, gstreamer receives the audiostream from the mic, the button 
>changes to "stop" and the vader sets to work breaking the audio stream into 
>utterances for pocketsphinx to process/convert to text. The output from 
>pocketshinx, what the engine thinks you said, is displayed in real time in the 
>text box of the gui.
>
>
>I want that text directed into the python program for further processing 
>instead of the text box.
>
>
>regards, Richard
>
>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Binary Addition

2013-01-12 Thread Ali Raza Ghasemi
Hi, the program that I sent you is not homework. It is merely something I did 
in my free time. I don't know what you mean so can you make it a little bit 
clearer by sending me the code.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with calling class methods stored in a list

2013-01-12 Thread Tobias M.

Peter Otten wrote:

You are right; the misunderstanding is that I wasn't advertising the above
"fancy" solution (which is buggy, btw).

Yes, I wasn't sure about the irony in you last post ;)

Peter Otten wrote:


I have now implemented what I had in mind with the protocol to function name
mapping, and I think /that/ is reasonably complex. I'm using instance
methods in the demo, but it should work with class methods as well.

class Error(Exception):
 def __init__(self, protocol):
 Exception.__init__(self, self.template.format(protocol))

class UnknownProtocolError(Error):
 template = "Unknown protocol {}"

class ProtocolNotSupportedError(Error):
 template = "Protocol {} not supported"

FOO = (42, 17)
BAR = (1, 2)
BAZ = (3, 4)
HAM = (4, 5)
SPAM = (5, 6)

class HandlersBase(object):
 protocol_to_methodname = {
 FOO: "foo",
 BAR: "bar",
 BAZ: "baz",
 HAM: "ham",
 }
 def get_handler(self, protocol):
 try:
 methodname = self.protocol_to_methodname[protocol]
 except KeyError:
 raise UnknownProtocolError(protocol)
 
 method = getattr(self, methodname, None)

 if method is None:
 raise ProtocolNotSupportedError(protocol)
 return method

class A(HandlersBase):
 def foo(self): print "A.foo"
 def bar(self): print "A.bar"
 def baz(self): print "A.baz"
 
class B(A):

 def bar(self): print "B.bar"
 baz = None # hide parent implementation

if __name__ == "__main__":

 for Class in A, B:
 inst = Class()
 print "---", Class.__name__, "---"
 for protocol in FOO, BAR, BAZ, SPAM:
 try:
 inst.get_handler(protocol)()
 except Error as err:
 print err
Thanks for the code! It's very similar to what I implemented but more 
flexible regarding inheritance.

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


Re: [Tutor] (no subject)

2013-01-12 Thread Dave Angel
On 01/12/2013 12:32 PM, Ali Raza Ghasemi wrote:
> I have to make a program that adds binary numbers together. The program has 
> to accept two binary values (up to 8 binary digits) and output their total in 
> binary. The output should not contain any leading zeros.
> I have a problem in that I don't know how to limit the number digits to 8 as 
> it accepts however many digits you enter, I also want the  program to ignore 
> anything other than 8-bit 0s and 1s. It is a python version 3.2.3
> Here is my code:
>
> def add_binary_numbers(num1, num2):
> while True:
> return num1 + num2
> if len(str(num1)) > 8:
> print("Please enter an 8 bit binary number")
> continue"
> num1 = int(input('please enter the first 8 bit binary number: '),2)
> num2 = int(input('please enter the second 8 bit binary number: '),2)
> result = add_binary_numbers(num1, num2)
> print('the result is', bin(result)[2:])
>
>

See yesterday's thread in this same mailing list entitled
"Binary/Decimal convertor"  probably started by a classmate.



-- 

DaveA

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


Re: [Tutor] (no subject)

2013-01-12 Thread Joel Goldstick
First, you need to type in a useful subject line for your question.
Second, it is nicer if you use plain text instead of rtf because rtf messes
up indentations sometimes.

This looks like homework.  That's ok.  But you should say so.  You haven't
really asked a question.  You state the assignment, then say that you don't
know how to deal with the 8 digit limit.

The int() function will raise a value error if you give it a number that
doesn't work for the base you set:

>>> int('123',2)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 2: '123'
>>>

So, you could write a small function that reads in the user's data and then
checks its length and whether it doesn't raise the V alueError
If it passes both tests, return its value.  Call it again for the second
number. Since you ask a different prompt for each number, you should pass
the prompt into your function as a parameter.  Add the two values, convert
to binary, and display your result


On Sat, Jan 12, 2013 at 12:32 PM, Ali Raza Ghasemi <
ghasem...@leedslearning.net> wrote:

>  I have to make a program that adds binary numbers together. The program
> has to accept two binary values (up to 8 binary digits) and output their
> total in binary. The output should not contain any leading zeros.
> I have a problem in that I don't know how to limit the number digits to 8
> as it accepts however many digits you enter, I also want the  program to
> ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3
> Here is my code:
>
> def add_binary_numbers(num1, num2):
> while True:
> return num1 + num2
> if len(str(num1)) > 8:
> print("Please enter an 8 bit binary number")
> continue
> num1 = int(input('please enter the first 8 bit binary number: '),2)
> num2 = int(input('please enter the second 8 bit binary number: '),2)
> result = add_binary_numbers(num1, num2)
> print('the result is', bin(result)[2:])
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


[Tutor] (no subject)

2013-01-12 Thread Ali Raza Ghasemi
I have to make a program that adds binary numbers together. The program has to 
accept two binary values (up to 8 binary digits) and output their total in 
binary. The output should not contain any leading zeros.
I have a problem in that I don't know how to limit the number digits to 8 as it 
accepts however many digits you enter, I also want the  program to ignore 
anything other than 8-bit 0s and 1s. It is a python version 3.2.3
Here is my code:

def add_binary_numbers(num1, num2):
while True:
return num1 + num2
if len(str(num1)) > 8:
print("Please enter an 8 bit binary number")
continue
num1 = int(input('please enter the first 8 bit binary number: '),2)
num2 = int(input('please enter the second 8 bit binary number: '),2)
result = add_binary_numbers(num1, num2)
print('the result is', bin(result)[2:])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Working with output of a subprocess

2013-01-12 Thread Jan Riechers

On 12.01.2013 00:29, 3n2 Solutions wrote:

Need some help with working with a text file.
Is it possible to get the values associated with each of the parameter
in the below text file format? For example:

1. How can I check what the Min and Max values are?
2. How to check the second column value associated with "epoch2"?




Examining file: 5521W231.txt

Duration :  0h : 59m
First meas : week   :  86 :   1721
Last  meas : week   :  89 :   1721

Min val   : 15
Max val : 18
3D :   3600  100.0%

summary Total  MissedRate
epoch1:1378   0   0\1000
epoch2:2154   1   0\1000



Alan's approach, writing a parser is right, just what I might want to add.

Just by looking at the general structure of the file:

For example the line:
"epoch1:1378   0   0\1000"
its like:

command/parameter TAB TAB ":" value TAB value TAB value"\"secondValue

Having a deeper look:
1) go line by line and check if the line starts with a searched value, 
like said
2) use a split to break up the structure of that line if its a command 
you want to get the values from, diving it to command, value pair using 
":" as a split character (for the epoch line)


Now you could split the value part result[2] = result[2].split('\t')
by "\t" tabulator sign and access the subvalues of that.

So the structure will be something like, after the 2nd split:
['epoch1', [1378, 0, '0\1000']]

If you encounter that there are tabs inside the command result, you can 
use str.rstrip('\t') to cut off tabs.


To avoid that the timestamp gets broken up into two parts, use 
str.split(':', 1) (only one split of that line) or similar.


Hope that helps.

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


Re: [Tutor] Is a link broken?

2013-01-12 Thread Steven D'Aprano

On 12/01/13 13:47, Ed Owens wrote:


I've written an example that I hope illustrates my problem:

#!/usr/bin/env python

import urllib2

sites = ('http://www.catb.org', 'http://ons-sa.org', 'www.notasite.org')
for site in sites:
try:
page = urllib2.urlopen(site)
print page.geturl(), "didn't return error on open"
print 'Reported server is', page.info()['Server']
except:
print site, 'generated an error on open'


Incorrect. Your "except" clause is too general, and so the error message
is misleading. The correct error message should be:

print site, """something went wrong in either opening the url,
getting the url, fetching info about the page, printing the
results, or something completely unrelated to any of those
things, or the user typed Ctrl-C to interrupt processing,
or something that I haven't thought of...
"""


Which of course is so general that it is useless.

Lesson 1: never, ever use a bare "except" clause. (For experts only:
almost never use a bare "except" clause.) Always specify what sort
of exceptions you wish to catch.

Lesson 2: always keep the amount of code inside a "try" clause to the
minimum needed.

Lesson 3: whenever possible, *don't* catch exceptions at all. It is
infinitely better to get a full exception, with lots of useful
debugging information, that to catch the exception, throw away that
useful debugging information, and replace it with a lame and useless
error message like "generated an error on open".

What sort of error?

What generated that error?

What error code was it?

Is it a permanent error (e.g. like error 404, page not found) or a
temporary error?

Is the error at the HTTP level, or the lower networking level, or
a bug in your Python code?


These are all vital questions that can be answered by inspecting
the exception and stack trace that Python gives you. The error
message "generated an error on open" is not only *useless*, but it
is also *wrong*.


I recommend that you start by not catching any exception at all. Just
let the exception (if any) print as normal, and see what you can learn
from that.




Site 1 is alive, the other two dead.


Incorrect.

Both site 1 and site 2 work in my browser. Try it and see for yourself.



Yet this code only returns an error on site three. Notice that I
checked for a redirection (I think) of the site if it opened, and that
didn't help with site two.


There is no redirection with site 2.



Is there an unambiguous way to determine if a link has died -- knowing
nothing about the link in advance?


No.

Define "line has died". That could mean:

- the individual page is gone;

- the entire web server is not responding;

- the web server is responding, but slowly, and requests time-out;

- the web server does respond, but only to say "sorry, too busy to
  talk now, try again later";

- the web server refuses to respond because you haven't logged in;

- you have a low-level network error, but the site is still okay;

- your network connection is down;

etc. There are literally dozens upon dozens of different types of
errors here.


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


Re: [Tutor] garbage collection/class question

2013-01-12 Thread Jan Riechers

On 12.01.2013 11:24, Alan Gauld wrote:

On 12/01/13 08:09, Jan Riechers wrote:


So to rephrase what you and also other wrote:
By setting "oakTree = Tree()" I create a new "Tree()" class instance.
Now calls to "oakTree.grow()" access functions of the Tree class, by
traversing to it's "Superclass" Tree.


No, they traverse to its Tree class. Superclasses are only involved when
you use inheritance. Consider:

class Tree:
def __init__(self,height=0):
  self.height = height

def getHeight(self):
   return self.height

def EverGreen(Tree):# subclass of Tree
def __init__(self, height=0, color='green'):
Tree.__init__(self,height)
self.color = color

def getColor(self):
return self.color


t = Tree()
print t.getHeight() # calls Tree.getHeight

g = EverGreen()
print g.getHeight()# calls Tree.getHeight by searching superclass
print g.getColor() # calls EverGreen.getColor

So the superclass is only used in the case of g.getHeight()
Python looks for getHeight in the class of EverGreen and can't find it.
So it looks in the superclass Tree to see if it can find getHeight there.



Actually I miss the terminology but that was what I thought to describe 
- also referring to your initial post on my question. If a class is 
based on a super class, the message lookup traversal goes from child to 
superclass, which now makes sense.




The "self" then, which also is used in the Superclass Function only
tells, work with the "own" (self) values of the class instance, instead
of the values of the class itself.

I guess that's right.


Maybe, I'm not sure what you mean. self is a reference to the instance
invoking the method.



Given:

class Market():
def __init__(self):
self.traders = 0

def addTrader(self):
self.traders += 1

instanceMarket = market()
print instanceMarket.traders # 0
instanceMarket.addTrader()
print instanceMarket.traders # 1

So the value of "traders" is unique to the instance, but the class 
function "addTrader", refers to the instance on which the function is 
invoked on (using self), but is declared only once for all instances 
based on "market". That also does now make sense. :)



Actually Im puzzled with the difference between a classmethod and a
regular function definition inside a class object.


All methods are functions defined inside classes. "regular functions"
are by definition NOT defined in a class. regular functions require no
lookup mechanism and do not have a "magic" first parameter like self.


Does the classmethod just mean that I can use the class "math" and call
"math.random()" without creating an instance of math before using
"random()" ?


Maybe, if math were a class. But math is actually a module which is
different to a class.



I think again the terms are mixing things up.
I tried that with the "classmethod" decorator and ended up with 
something like this:

class market():
__balance = 500

@classmethod
def getBalance(cls):
print cls.__balance


In this case now, from what was explained and what meant to say,
market.getBalance() can now called without creating an instance of that 
class (like a module, even so it is not.)


So calling:
market.getBalance() # --> 500


Okay, that makes sense - that class functions/methods (confusing with
that decorator to talk about)


The decorator is only used for classmethods not for instance methods.
Most of the time you don't need to use classmethods you only need
instance methods.

Sorry again for the long post and mixing up the wordings, I guess I have 
to practice and read a bit more, but I understand now more of the OOP 
concept and inner workings than before - so it helped already :)


Jan


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


Re: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package )

2013-01-12 Thread eryksun
On Fri, Jan 11, 2013 at 7:12 PM, somnath chakrabarti
 wrote:
>
> Actually the problem was the access permission for the destination folder. I
> changed to my account-specific path and it worked.

You should be OK using gcc as long as you're not using C++. But why
not use Microsoft's free (as in beer) compiler from the Windows 7 SDK?

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


Re: [Tutor] garbage collection/class question

2013-01-12 Thread Alan Gauld

On 12/01/13 08:09, Jan Riechers wrote:


So to rephrase what you and also other wrote:
By setting "oakTree = Tree()" I create a new "Tree()" class instance.
Now calls to "oakTree.grow()" access functions of the Tree class, by
traversing to it's "Superclass" Tree.


No, they traverse to its Tree class. Superclasses are only involved when 
you use inheritance. Consider:


class Tree:
   def __init__(self,height=0):
 self.height = height

   def getHeight(self):
  return self.height

def EverGreen(Tree):# subclass of Tree
   def __init__(self, height=0, color='green'):
   Tree.__init__(self,height)
   self.color = color

   def getColor(self):
   return self.color


t = Tree()
print t.getHeight() # calls Tree.getHeight

g = EverGreen()
print g.getHeight()# calls Tree.getHeight by searching superclass
print g.getColor() # calls EverGreen.getColor

So the superclass is only used in the case of g.getHeight()
Python looks for getHeight in the class of EverGreen and can't find it. 
So it looks in the superclass Tree to see if it can find getHeight there.



The "self" then, which also is used in the Superclass Function only
tells, work with the "own" (self) values of the class instance, instead
of the values of the class itself.

I guess that's right.


Maybe, I'm not sure what you mean. self is a reference to the instance 
invoking the method.



Actually Im puzzled with the difference between a classmethod and a
regular function definition inside a class object.


All methods are functions defined inside classes. "regular functions" 
are by definition NOT defined in a class. regular functions require no 
lookup mechanism and do not have a "magic" first parameter like self.



Does the classmethod just mean that I can use the class "math" and call
"math.random()" without creating an instance of math before using
"random()" ?


Maybe, if math were a class. But math is actually a module which is 
different to a class.



Okay, that makes sense - that class functions/methods (confusing with
that decorator to talk about)


The decorator is only used for classmethods not for instance methods.
Most of the time you don't need to use classmethods you only need 
instance methods.




--
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] run perl script files and capture results

2013-01-12 Thread eryksun
On Fri, Jan 11, 2013 at 7:33 PM, Prasad, Ramit
 wrote:
>
> Why not just use r'C:\Python27\\'? Might be too confusing for
> a beginner to remember, I suppose.

Off the top of my heard I can think of 3 raw-escape uses of backslash
in a raw string literal: placing an even number of backslashes at the
end of the literal (an odd number is a syntax error), including the
quote character, and raw line continuation (includes the LF):

>>> list(r'\\')
['\\', '\\']

>>> list(r'\'')
['\\', "'"]

>>> list(r"\"")
['\\', '"']

>>> s = r'\
... '
>>> list(s)
['\\', '\n']
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collection/class question

2013-01-12 Thread Jan Riechers

On 12.01.2013 02:19, Mitya Sirenef wrote:


Functions are the same, (called methods), but the self object is
different for each instance, and represents the instance. Consider that
since the logic performed by the method is the same (if it wasn't, you'd
define it as a separate method, right?), there would be no reason to
make a separate method for each instance. As you know from working with
functions, the same function may create different output if its
arguments are different (from another call), but if the arguments are
the same, it will create the same output (I'm ignoring things like
random module).

Well, that's why the first argument for a method is 'self', which is
different for each instance.





So to rephrase what you and also other wrote:
By setting "oakTree = Tree()" I create a new "Tree()" class instance.
Now calls to "oakTree.grow()" access functions of the Tree class, by 
traversing to it's "Superclass" Tree.


The "self" then, which also is used in the Superclass Function only 
tells, work with the "own" (self) values of the class instance, instead 
of the values of the class itself.


I guess that's right.




The core idea of having a class and one or more instances is very
versatile and powerful, all of the other concepts are much less needed
especially as you're starting out. For example, you can have a class
tree and methods and a bunch of tree instances; a classmethod would
allow you to perform an action without making an instance first, but
it's not like it's hard to make an instance -- it's just that in some
cases it's clearer and more straightforward to use a classmethod, like
Alan pointed out, but if you happen to forget about classmethods, you
could easily get by without them. The same applies to Borg pattern, etc.



Actually Im puzzled with the difference between a classmethod and a 
regular function definition inside a class object.


Does the classmethod just mean that I can use the class "math" and call 
"math.random()" without creating an instance of math before using 
"random()" ?

To what you write, it would make sense like that.

Of course the math module has to be imported first. But thats not the 
point now I guess :)



 > So I assume the functions are shared across thus one decleration has
been made in "Tree" class and all siblings are using that one?


They are usually called methods if they belong to a class, and yes
they're shared.



Okay, that makes sense - that class functions/methods (confusing with 
that decorator to talk about) are accessible and shared across all class 
instances - and its also what I noticed by using some code like 
following and the id() function.


Dave was asking what code I meant to get the "memory address" on where a 
function is lurking:


-

class market():
def __init__(self):
self.name = 'Market'
def getMarketPrice(self):
print self
print self.__dict__


myInstancesList = []

for x in range(0, 10):
myInstancesList.append( market() )
print id(myInstancesList[x].getMarketPrice)

print myInstancesList

-

Which outputs the same memory reference for the function 
"getMarketPrice" of all instances of the "market" class plus the 
instances inside a list "myInstancesList".


I dont use a dictionary which might be confusing, but makes more sense 
to work with.


Also id() mentioned here: 
http://stackoverflow.com/questions/121396/accessing-object-memory-address


And thank you all for the explanations. :)

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