Re: [Tutor] Please help understanding unittest fixtures

2011-08-22 Thread Peter Otten
Steven D'Aprano wrote:

> D. Guandalino wrote:

>> In this case is there a
>> way to force just one setUp() call?
> 
> 
> I don't know if this is the best way, but the first way that comes to
> mind is this:
> 
> 
> class C(TestCase):
>  initialised = False
>  def setUp(self):
>  if self.initialised:
>  return
>  # Make sure you save the flag on the class, not the instance!
>  self.__class__.initialised = True
>  ...

Python 2.7 and 3.2 support setUpClass()/tearDownClass() classmethods, see

http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass

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


Re: [Tutor] Where is sys.py?

2011-08-22 Thread Lisi
On Monday 22 August 2011 00:13:37 Steven D'Aprano wrote:
> > The modules within it must surely be somewhere too.  But since I can't
> > find sys, I obviously can't find the modules.  Again, I'd like to look at
> > them.
>
> I don't understand what you mean by "modules within it".

The problem may be that I have again failed to understand.

As I understand it, I can, should I wish to do so, write and save a subroutine 
that I wish to reuse rather than write the same subroutine out multiple 
times.

The book also says that one can import sys and then run the various commands 
within it.  It also appears to say that sys is a file, and I thought that it 
said sys.py existed.  Clearly, it didn't since it doesn't.

Anyhow, I therefore thought - erroneously - that if there could be commands in 
sys, then it must be possible to store subroutines in some sort of "envelope" 
so that I could import the "envelope" and call the subroutines as I wanted 
them.  Otherwise, storing short subroutines would appear to me to be a waste 
of time and effort.  By the time one has imported the subroutine and then run 
it, and done this for every one of a number of short subroutines, it would be 
quicker and easier just to run them when needed.

So I wanted to look at how Python itself does it, so that I could copy it.

a) I am clearly barking up a non-existent tree and b) the sooner I forget 
completely about the text that I was working from (I am still turning over in 
my mind the exercise I got hung up on) and focus only on Alan's, the sooner I 
am going to make some kind of progress!!

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


Re: [Tutor] Where is sys.py?

2011-08-22 Thread Emile van Sebille

On 8/22/2011 6:45 AM Lisi said...

On Monday 22 August 2011 00:13:37 Steven D'Aprano wrote:

The modules within it must surely be somewhere too.  But since I can't
find sys, I obviously can't find the modules.  Again, I'd like to look at
them.


I don't understand what you mean by "modules within it".


The problem may be that I have again failed to understand.


Actually, sys retains a reference to all imported modules in sys.modules 
and that gives a pretty good idea of where stuff comes from(tm).  :)




>>> from pprint import pprint as pp
>>> pp(sys.modules)
{'UserDict': ,
 '__builtin__': ,
 '__main__': ,
 '_abcoll': ,
 '_codecs': ,
 '_functools': ,
 '_locale': ,
 '_sre': ,
 '_warnings': ,
 'abc': ,
 'cStringIO': ,
 'codecs': ,
 'copy_reg': ,
 'encodings': 'C:\Python26\lib\encodings\__init__.pyc'>,

 'encodings.__builtin__': None,
 'encodings.aliases': 'C:\Python26\lib\encodings\aliases.pyc'>,

 'encodings.codecs': None,
 'encodings.cp1252': 'C:\Python26\lib\encodings\cp1252.pyc'>,
 'encodings.cp437': 'C:\Python26\lib\encodings\cp437.pyc'>,

 'encodings.encodings': None,
 'errno': ,
 'exceptions': ,
 'functools': ,
 'genericpath': 'C:\Python26\lib\genericpath.pyc'>,

 'linecache': ,
 'locale': ,
 'nt': ,
 'ntpath': ,
 'operator': ,
 'os': ,
 'os.path': ,
 'pprint': ,
 're': ,
 'signal': ,
 'site': ,
 'sre_compile': 'C:\Python26\lib\sre_compile.pyc'>,
 'sre_constants': 'C:\Python26\lib\sre_constants.pyc'>,

 'sre_parse': ,
 'stat': ,
 'sys': ,
 'types': ,
 'warnings': ,
 'zipimport': }

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


Re: [Tutor] Where is sys.py?

2011-08-22 Thread Lisi
On Monday 22 August 2011 15:09:45 Emile van Sebille wrote:
> Actually, sys retains a reference to all imported modules in sys.modules
> and that gives a pretty good idea of where stuff comes from(tm).  :)

[snip interesting file]

Thanks, Emile. :-)

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


[Tutor] Making a Python Window

2011-08-22 Thread Susana Iraiis Delgado Rodriguez
Hello List!!

I want to start desingning and developing python interfaces, but I don't
know what library or tool can help me to accomplish my goal. I have
installed the 2.6.6 python interpreter version, my operative system is
Windows XP. The interfaces I want to create will be very simple, just to
select a directory, entry some text, etc.
What will be the best option?
Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] return all the days between two dates using the calendar module

2011-08-22 Thread Norman Khine
Hello,
I have this code http://pastie.org/2411735 which basically reads a CSV
file, takes the date field and then for each day executes an SQL query
to pull the amount of orders that have been generated.

My issue I have is that on the back-office of the e-commerce package
the total orders for the same range of time returns different amount,
even though the SQL is correct.

One possible error may occur from the fact that I am using the CSV
file for the date range, rather than the calendar module, and I am
unsure how to return the list of dates for a given range. So in line
72, rather then using the dates in the CSV file I would like to build
this list from the calendar module.

I got this, http://pastie.org/2411864 but this just adds a day and is
not 100% precise.

Any advice much appreciated.

Norman

-- 
˙ʇı ɹoɟ ƃuıʎɐd ǝɹ,noʎ ʍou puɐ ǝɔıoɥɔ ɐ ʞooʇ ı ʇɐɥʇ sı 'ʇlnɔıɟɟıp sı ʇɐɥʍ
˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ
ǝq s,ʇǝן ʇǝʎ
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Where is sys.py?

2011-08-22 Thread Alan Gauld

On 22/08/11 14:45, Lisi wrote:


I don't understand what you mean by "modules within it".


The problem may be that I have again failed to understand.

As I understand it, I can, should I wish to do so, write and save a subroutine
that I wish to reuse rather than write the same subroutine out multiple
times.


That's correct


The book also says that one can import sys and then run the various commands
within it.  It also appears to say that sys is a file, and I thought that it
said sys.py existed.  Clearly, it didn't since it doesn't.


I hope that's not my tutorial you are reading? :-)
If so, you missed the bit in parentheses:

---
It is almost like making a copy the contents of sys.py into our program, 
like a cut n' paste operation. (it's not really like that but the 
concept is similar. In fact sys is a special kind of module that doesn't 
actually have a sys.py file, but we will ignore that for now!)




Anyhow, I therefore thought - erroneously - that if there could be commands in
sys, then it must be possible to store subroutines in some sort of "envelope"
so that I could import the "envelope" and call the subroutines as I wanted
them.  Otherwise, storing short subroutines would appear to me to be a waste
of time and effort.  By the time one has imported the subroutine and then run
it, and done this for every one of a number of short subroutines, it would be
quicker and easier just to run them when needed.


Now I'm confused.
There can be functions inside a module but not commands, they are 
technically something different and only exist within the Python 
interpreter itself. And you can access those functions from the module 
after you have imported it.


I'm not sure what you mean by an envelope though?
The module is the envelope...

And I don't understand the bit about the time taken for short routines?
Do you mean the time taken to access them in terms of typing time? Or in 
terms of execution time? It is faster to import than the time it takes 
to retype a function unless the function is only a simple expression.


def foo(x): return x+1

is 22 characters. If saved in a module called foo.py it can be used with

import foo

Which is 10 characters.

and used with

foo.foo(5)

which is only 4 extra characters, that's a lot less than retyping the 
definition. And if you expect to type foo. a lot then use:


from foo import foo

which is still only 19 characters, less than the definition.
So even for this trivially simple case its still faster to put foo into 
a module...



So I wanted to look at how Python itself does it, so that I could copy it.

a) I am clearly barking up a non-existent tree and b) the sooner I forget
completely about the text that I was working from (I am still turning over in
my mind the exercise I got hung up on) and focus only on Alan's, the sooner I
am going to make some kind of progress!!


There seems to be some strange terminology creeping in but whether 
that's down to your text (looks like its not mine! :-) or just your own 
preconceptions I'm not sure.


One advantage of using mine is that you know where to find me if you 
don't understand something! :-)


--
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] Making a Python Window

2011-08-22 Thread Alan Gauld

On 22/08/11 16:21, Susana Iraiis Delgado Rodriguez wrote:


I want to start desingning and developing python interfaces, but I don't
know what library or tool can help me to accomplish my goal.


Three are pros and cons to all the different options available.

My personal recommendation is to use Tkinter, purely because it comes 
with Python and is one of the easiest to learn.


wxPython and PyQt and pyGTK are all valid alternatives but you need to 
download and install them. Tkinter comes in the standard library.



Windows XP. The interfaces I want to create will be very simple, just to
select a directory, entry some text, etc.


You might find easyGUI is sufficient for your needs but its not a full 
GUI tool, it just makes using Python in a GUI environment slightly more 
user friendly.


Personally I'd stick with Tkinter.

You can find a short introduction to GUI programming in my tutorial, and 
it covers Tkinter and a short comparative example using wxPython.
The latter is definitely a better bet if you want to move on to more 
sophisticated UIs, especially if you want to include features like 
printing (surprisingly difficult on Windows!)


--
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] Where to direct non-language questions?

2011-08-22 Thread Michael Scharf
On Sat, Aug 13, 2011 at 3:58 AM, Steven D'Aprano  wrote:
> Michael Scharf wrote:
>>
>> Sent: Friday, August 12, 2011 3:54 PM
>>
>> Hi List,
>>
>> I'm am not quite at the point of needing this, but where would I go to
>> ask a question like "Why is the OpenCalais Python API not returning
>> all fields when I do x or y"  or "Has anyone built their own Python
>> API for OpenCalais"?  Stack Overflow? Or is there something
>> Python-specific?
>
> Something as specific as the first question is best asked on whatever forum
> the OpenCalais Python library makes available: a mailing list, a bug
> tracker, the author's personal email, an IRC channel. The second question
> should be asked on whatever forums specialise in OpenCalais.
>
> Failing that, you could try comp.lang.python, which tends to have a lot more
> people that here. If you don't have access to Usenet, it is also available
> on python-l...@python.org.
>
>
>
>
> --
> Steven
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

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


Re: [Tutor] Making a Python Window

2011-08-22 Thread Susana Iraiis Delgado Rodriguez
Hello Alan!!

Thank you for tha advice! I'll look at your tutorial, and test the options
you're giving to me.
Thank you
2011/8/22 Alan Gauld 

> On 22/08/11 16:21, Susana Iraiis Delgado Rodriguez wrote:
>
>  I want to start desingning and developing python interfaces, but I don't
>> know what library or tool can help me to accomplish my goal.
>>
>
> Three are pros and cons to all the different options available.
>
> My personal recommendation is to use Tkinter, purely because it comes with
> Python and is one of the easiest to learn.
>
> wxPython and PyQt and pyGTK are all valid alternatives but you need to
> download and install them. Tkinter comes in the standard library.
>
>
>  Windows XP. The interfaces I want to create will be very simple, just to
>> select a directory, entry some text, etc.
>>
>
> You might find easyGUI is sufficient for your needs but its not a full GUI
> tool, it just makes using Python in a GUI environment slightly more user
> friendly.
>
> Personally I'd stick with Tkinter.
>
> You can find a short introduction to GUI programming in my tutorial, and it
> covers Tkinter and a short comparative example using wxPython.
> The latter is definitely a better bet if you want to move on to more
> sophisticated UIs, especially if you want to include features like printing
> (surprisingly difficult on Windows!)
>
> --
> 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] Where is sys.py?

2011-08-22 Thread Lisi
On Monday 22 August 2011 17:31:41 Alan Gauld wrote:
> Now I'm confused.

Yes, I'm afraid that _I_ was very confused.  I am gradually getting the mess 
in my head disentangled.

> There can be functions inside a module but not commands, they are
> technically something different and only exist within the Python
> interpreter itself. And you can access those functions from the module
> after you have imported it.
>
> I'm not sure what you mean by an envelope though?
> The module is the envelope...

By "envelope" I meant container, because I was afraid of misusing the correct 
technical terms.  I am still very confused by the terminology.  Having been 
told that modules, functions and methods are just different names for the 
same thing, that commands are really also the same thing and having had them 
called yet a fifth thing in order "not to confuse you" (ouch!!) I am in a 
right muddle.  What I am doing at the moment is trying to sort out the muddle 
in my own head.  You have no idea what a relief it was to be told (by you 
Alan in your text) that a function is a sub-routine.  I know what a 
sub-routine is!  And I shall just go on asking questions until I have got the 
whole thing disentangled in my head.  Sorry, everybody.  (Unlearning 
something is much harder than learning it.)

Alan, I did enjoy playing around with address books, which I can see have some 
point, instead of chasing bears, lollipops and flowers, or whatever it 
was. :-( 

So now, can anyone suggest an example of a module to look at?  (Preferably 
with some subroutines inside).It is clearly NOT just another name for 
function or method.  I imagine that there are some on the Internet?

> And I don't understand the bit about the time taken for short routines?
> Do you mean the time taken to access them in terms of typing time? Or in
> terms of execution time? It is faster to import than the time it takes
> to retype a function unless the function is only a simple expression.

I hadn't actually counted the keystrokes.  I stand corrected.  But saving 6 
keystrokes is still a fairly pointless thing to do.  If several subroutines 
can be stored in a module and imported together, then that is quite another 
matter.

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


Re: [Tutor] return all the days between two dates using the calendar module

2011-08-22 Thread Norman Khine
ok ignore, this works

def date_range(start_date, end_date):
r = (end_date+datetime.timedelta(days=1)-start_date).days
return [start_date+datetime.timedelta(days=i) for i in range(r)]



On Mon, Aug 22, 2011 at 5:27 PM, Norman Khine  wrote:
> Hello,
> I have this code http://pastie.org/2411735 which basically reads a CSV
> file, takes the date field and then for each day executes an SQL query
> to pull the amount of orders that have been generated.
>
> My issue I have is that on the back-office of the e-commerce package
> the total orders for the same range of time returns different amount,
> even though the SQL is correct.
>
> One possible error may occur from the fact that I am using the CSV
> file for the date range, rather than the calendar module, and I am
> unsure how to return the list of dates for a given range. So in line
> 72, rather then using the dates in the CSV file I would like to build
> this list from the calendar module.
>
> I got this, http://pastie.org/2411864 but this just adds a day and is
> not 100% precise.
>
> Any advice much appreciated.
>
> Norman
>
> --
> ˙ʇı ɹoɟ ƃuıʎɐd ǝɹ,noʎ ʍou puɐ ǝɔıoɥɔ ɐ ʞooʇ ı ʇɐɥʇ sı 'ʇlnɔıɟɟıp sı ʇɐɥʍ
> ˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ
> ǝq s,ʇǝן ʇǝʎ
> %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
> chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
>



-- 
˙ʇı ɹoɟ ƃuıʎɐd ǝɹ,noʎ ʍou puɐ ǝɔıoɥɔ ɐ ʞooʇ ı ʇɐɥʇ sı 'ʇlnɔıɟɟıp sı ʇɐɥʍ
˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ
ǝq s,ʇǝן ʇǝʎ
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Where is sys.py?

2011-08-22 Thread Steven D'Aprano

Lisi wrote:

By "envelope" I meant container, because I was afraid of misusing the correct 
technical terms.  I am still very confused by the terminology.  Having been 
told that modules, functions and methods are just different names for the 
same thing, that commands are really also the same thing and having had them 
called yet a fifth thing in order "not to confuse you" (ouch!!) I am in a 
right muddle.


Ayyeee You have my sympathy!


Okay, let's start with the basics. Here's a small piece of simple Python 
code, to count down from ten:



for i in range(10, 0, -1):
print(i)

print("Lift off!")


If you type that in the interactive interpreter, and hit Enter, Python 
will execute that code and print 10 9 8 ... 2 1 Lift off!


Suppose you want to do a count-down again. In the interpreter, you would 
have to type out the whole thing again. This is annoying and frustrating 
-- imagine if you wanted to run it a thousand times. So instead, we can 
make a re-usable, named, piece of code: a function.


def countdown():
for i in range(10, 0, -1):
print(i)
print("Lift off!")


If you type that in, once, it defines a reusable piece of code called 
"countdown". Now you can run that code as many times as you like, by typing:


countdown()

and then hitting Enter. Much simpler, with much less chance of error.

Note that the parentheses are required. Without the round brackets, the 
code inside the function won't be run.


(Methods are very similar to functions. At the most basic level, we can 
pretend that a method is just a function that comes stuck to something 
else. Don't worry about methods for now.)


But the problem here is that the countdown function is not permanent. If 
you exit the interpreter, and start again, it will be lost for good. The 
solution is to save the function in a .py file -- a module.


So in your text editor, type

def countdown():
for i in range(10, 0, -1):
print(i)
print("Lift off!")


in the file, save the file as "example.py". This becomes a module. A 
module can contain any Python code you like: one line or a thousand, one 
function or a hundred functions, or anything else.


Then, later, you can restart the Python interpreter, give the command:

from example import countdown

and use countdown as if you had just typed it in by hand.

Sometimes people will use "function" and "command" interchangeably. I 
don't like this. Commands (also known as statements) are always built-in 
to Python and operate as *instructions* to the interpreter. There are 
only a few:


import ...
from ... import ...
def
class
del
print (Python 2 only, in Python 3 it becomes a function)

are the main ones. (There may be a few more I have missed.) Such 
commands generally don't use parentheses, except for grouping items.


Functions always require parentheses. They may be built-in, such as len, 
or you can write your own, using the def command.


Functions also always return a result, so you can do this:

x = some_function(a, b, c)

Commands don't. You can't say:

x = del a, b, c

because del doesn't return anything. Since it doesn't return anything, 
you can't save the result in x.


(Aside: you can create functions that mimic commands by returning the 
special value None. That's used for functions which are intended to not 
return a value, but since Python requires functions to return something, 
they return the special value None to mean "ignore this, it's nothing". 
But they're still functions, and they still return something: the 
special value None.)


So, summary:

* Commands are built-in Python instructions;
* Sometimes also known as "statements".
* They take actions, but don't return a result.
* "Command" is not an official Python term, so some people may
  disagree with me!


* Functions may be built-in, or defined by the user.
* Functions always return something.
* Functions can mimic commands by returning None. I call these
  "procedures", copying the language Pascal.
* Methods are related to functions.


* A module is a container that holds functions and any other values
  you like.
* Modules are NOT functions, although they can hold functions.
* Modules usually are loaded from .py files on your disk.
* When you import the module, Python runs the code inside the file,
  builds a module, and makes the module appear in the interpreter.
* Some special modules are built-in to the Python compiler, and
  don't exist in a .py file.
* Other modules come from DLLs or .so files, and are written in C.




So now, can anyone suggest an example of a module to look at?  (Preferably 
with some subroutines inside).It is clearly NOT just another name for 
function or method.  I imagine that there are some on the Internet?


The Python standard library consists of 200 or so Python files, all of 
which can be opened in a text editor and read or printed for study.


(Be careful not to make modifications to the files, since you risk 
breaking them and preventing Python from wo

Re: [Tutor] file fetcher class object through http

2011-08-22 Thread Prasad, Ramit
>Such tools already exist, although they may not be written in Python. In 
>particular, google on "wget" or "curl" for two very well-known 
>industrial-strength tools for downloading files from the web (and other 
>places). If you just want something that works, I recommend you learn 
>how to use those tools rather than re-inventing the wheel.

http://pycurl.sourceforge.net/ <- Python interface for curl.  

I have never used it, but it would probably do what you want. Normally I use 
os.system with wget, but it is a quick dirty hack.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] methods vs. functions

2011-08-22 Thread Prasad, Ramit
Steven D'Aprano wrote: 
>(Methods are very similar to functions. At the most basic level, we can 
>pretend that a method is just a function that comes stuck to something 
>else. Don't worry about methods for now.)

Can someone please explain the difference between methods and functions?

Thanks,
Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] methods vs. functions

2011-08-22 Thread TheIrda
Well, my understanding is that function are used in procedural programmming
to make the code reusable, and to divide the bigger problem in a serie of
 smaller ones.
Methods are used in OOP, and mainly are the actions taht objects can
perform.

Thay have a very similar syntax in python, but the concept is quite
different.
In the procedural programming you have the code that manipulare date to get
the result, while in OOP you have objects that act through methods to get
teh result.

At least this is my understanding :)

2011/8/22 Prasad, Ramit 

> Steven D'Aprano wrote:
> >(Methods are very similar to functions. At the most basic level, we can
> >pretend that a method is just a function that comes stuck to something
> >else. Don't worry about methods for now.)
>
> Can someone please explain the difference between methods and functions?
>
> Thanks,
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
> ___
> 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] Where is sys.py?

2011-08-22 Thread Lisi
Thanks, Steven, for an extremely helpful email.  I _think_ that I have now 
grasped it; tho' teh proof of teh pudding is in the eating. :-/

On Monday 22 August 2011 19:55:02 Steven D'Aprano wrote:
> Lisi wrote:  
   [snip] 

> Are you using Windows or Linux or Mac?

Linux Debian 6.

> On my Linux system, I can look inside:
>
> /usr/lib/python2.5/

and on mine.

> and see the Python modules.

Thanks again, Steven.
Lisi




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


Re: [Tutor] methods vs. functions

2011-08-22 Thread Wayne Werner
On Mon, Aug 22, 2011 at 3:11 PM, Prasad, Ramit wrote:

> Steven D'Aprano wrote:
> >(Methods are very similar to functions. At the most basic level, we can
> >pretend that a method is just a function that comes stuck to something
> >else. Don't worry about methods for now.)
>
> Can someone please explain the difference between methods and functions?
>
> Thanks,
> Ramit
>

You could define a function as a reusable section of related code.
Technically speaking, it doesn't have to be related, but that's bad
programming.

A method is a section of related code that is attached to related data.

For instance, say you have a string that you would like to reverse. How
would you do it, if Python didn't have batteries included?

Here's the functional way:

def string_reverse(string):
return_string = ""
for x in xrange(len(string)-1, -1, -1): # range in Python 3.x
return_string += string[x]
return return_string

mystring = "Norwegian Blue"
print(string_reverse(mystring))

However, if you wanted to view strings as objects - "things" if you will,
you can create a class:

class String:
def __init__(self, startvalue=""):
self.value = startvalue

def reverse(self):
self.value = self.value[::-1] # Using slicing

mystring = String("A Slug")
mystring.reverse()
print(mystring.value)


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


Re: [Tutor] methods vs. functions

2011-08-22 Thread Modulok
On 8/22/11, Prasad, Ramit  wrote:
> Steven D'Aprano wrote:
>>(Methods are very similar to functions. At the most basic level, we can
>>pretend that a method is just a function that comes stuck to something
>>else. Don't worry about methods for now.)
>
> Can someone please explain the difference between methods and functions?
>
> Thanks,
> Ramit

At the most basic level, they're the same. If you have a named, stand-alone
section of code that (optionally) operates on some argument passed to it, it's
called a function. If you have the same exact code, but you group it together
into a named unit along with the data it (optionally) operates on, it's called
a method. Technically in Python, they're both objects, both callables and can
be called in similar ways. The distinction is quite minimal. Here's a few
examples:


# A function that expects the first argument to be some object it operates on.
# This is just like a method, except it hasn't been declared within any class.
# Therefore, it's called a function:

def setx(foo):
foo.x = 1


# The same exact thing again, but declared in a 'Bar' class. Now it's
# called a method. Normally the first parameter to every instance method is
# named 'self', (A convention you should adhere to.) To make this example
# clearer, however, I use the name 'foo' instead just like the last example:

class Bar(object):
def setx(foo):
foo.x = 1


The call itself is a little different:

# As a function you must pass the arguments:

a = Bar()
setx(a) #<-- Explicitly pass the object as an argument.

# As a method the first argument is implied:

a = Bar()
a.setx()#<-- First argument is passed automatically for you.

That said, you could also call a method as if it were a function living in the
Bar namespace:

a = Bar()
Bar.setx(a)

You can even declare a function within a class that *doesn't* operate on any
instance of the class. Just like an ordinary function, you must pass all
arguments. This is called a static method and is declared with the
'@staticmethod' decorator:

class Baz(object):
@staticmethod
def bonzo(x, y):
return x+y

You can then call it like this:

Baz.bonzo(3, 5)

This looks remarably similar to calling a function that exists in some
namespace. For example:

import random
random.randrange(3, 5)


So the ultimate difference? Pretty much just where you declare it. If it's in a
class it's called a method, outside of a class its called a function.
Especially in python - the distinction is small.

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


Re: [Tutor] methods vs. functions

2011-08-22 Thread Robert Sjoblom
> Can someone please explain the difference between methods and functions?
I've heard the explanation "A cow is an animal but an animal is not
necessarily a cow." used to describe the difference between methods
and functions (ie, all methods are functions, but not all functions
are methods). Obviously, that's a horrible description.

This one's better:
A function is a piece of code that is called by name. It can be passed
data to operate on (ie. the parameters) and can optionally return data
(the return value).
All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by name that is associated
with an object. In most respects it is identical to a function except
for two key differences.
It is implicitly passed the object for which it was called
It is able to operate on data that is contained within the class
(remembering that an object is an instance of a class - the class is
the definition, the object is an instance of that data)

Credit where credit is due:
http://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function

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


Re: [Tutor] methods vs. functions

2011-08-22 Thread Alan Gauld

On 23/08/11 00:10, Robert Sjoblom wrote:

Can someone please explain the difference between methods and functions?


I'm sure if you go to Wikipedia you will get the correct computer 
science distinctions, however in practical terms and limiting the 
discussion to Python:



A function is a piece of code that is called by name. It can be passed
data to operate on (ie. the parameters) and can optionally return data
(the return value).


That's about right, except that both theoretically and in Python there 
is always a return value. If you don't specify it Python returns a 
default value of None. (In other languages a "function" that does not 
return a value is more correctly called a procedure)



All data that is passed to a function is explicitly passed.


That depends on how you define "passed to".
A function has visibility of the data in its surrounding
scope too. So

x = 42
def f():
   print x

f()

will print 42 because x is implicitly passed to f() by virtue
of being in the enclosing scope.


A method is a piece of code that is called by name that is associated
with an object. In most respects it is identical to a function except
for two key differences.
 It is implicitly passed the object for which it was called


Correct. A method is a function defined inside a class.
It is the function that the class calls on receipt of
a message passed to an object. It is therefore the method
by which the object fulfils the message request, hence the
name "method".


 It is able to operate on data that is contained within the class
(remembering that an object is an instance of a class - the class is
the definition, the object is an instance of that data)


That's more complicated. It can operate on data within the object by 
using the object reference passed to it. It can operate on data within 
the class (ie. class data not instance data) by reference to the class
in which it is defined. But in Python, unlike other languages, there is 
no "magic" visibility of these data attributes, it all happens via very 
explicit references.


Perhaps more important is that methods are part of the class heirarchy 
lookup mechanism. Thus a method may be executed by an object of another 
class if the other class inherits from the defining class.


class A:
   def f(self): print 'I'm in A'

class B(A): pass

a = A()
b = B()

for obj in (a,b):
   obj.f()

Method f() gets called for both objects even though it is only defined
in class A.

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] Where is sys.py?

2011-08-22 Thread Alan Gauld

On 22/08/11 18:38, Lisi wrote:


technical terms.  I am still very confused by the terminology.  Having been
told that modules, functions and methods are just different names for the
same thing, that commands are really also the same thing and having had them
called yet a fifth thing in order "not to confuse you" (ouch!!)


I see Steven has sent a very good reply, I'll add a slightly different 
slant but try not to confuse things further!


There is a loty of confusion and double definitions in Computing, mainly 
through history and the evolution of different languages etc.


There is also the difference between a computing concept, like a module, 
and the implementation of that concept in a given language. In general 
the concept will be a broader definition than the implementation.


So sub-routine comers from the world of assembler programming and was 
adopted by BASIC because BASIC was invented back in the 1960's when most 
folks were used to assembler. Function comes from math and is directly 
related to the math theory behind computing and was therefore introduced 
into theoretical biased languages like Algol.


Modularity is a design concept from the world of engineering.
sub routines and functions were early attempts to introduce
modularity into the world of computing. Gradually modularity was 
extended to include concepts like code libraries of 
sub-routines/functions and eventually the term module started to appwear 
in programming languages themselves - Modula, (and then Modula 2 and 
Modula 3) being I think the main source.


Commands are slightly different in that they look quite similar to 
functions but usually have slightly different calling syntax and they 
are usually built into the core language rather than being user defined( 
but as always exceptions exist so that Tcl for example allows you to 
define your own commands) In Python 2 the best known command is print. 
It has been turned into a function in Python v3, thus


in v2

print "Hello"

becomes, in V3

print("Hello")

Notice the addition of parentheses.

So what does all that mean in practice in Python?

Modules are files that contain any kind of arbitrary
python code that can be imported into other programs
and reused.

Very often Modules contain one or more function definitions.

Modules can also contain class definitions - classes are
another mechanism for providing modularity (the concept!)
in programs. Class definitions also contain functions (with
the special classification "method" - see another thread)
within them.

> I am in a right muddle.

It is entirely understandable. This is one of the most
confusing areas of computing.

> ...  And I shall just go on asking questions until I have got the

whole thing disentangled in my head.  Sorry, everybody.


Don't apologise, it's the right thing to do. And on a list like this you 
will almost certainly clarify things in a lot of other folks heads too, 
who may not have thought through the complexities for themselves yet.



So now, can anyone suggest an example of a module to look at?  (Preferably
with some subroutines inside).It is clearly NOT just another name for
function or method.  I imagine that there are some on the Internet?


Look in the standard library at glob.py
It is one of the few that doesn't confuse things with classes, it is 
just a collection of functions and not too complicated ones at that.
But being part of the standard library it has all the features that make 
a good reusable module too (documentation etc). And its not too big.



I hadn't actually counted the keystrokes.  I stand corrected.  But saving 6
keystrokes is still a fairly pointless thing to do.  If several subroutines
can be stored in a module and imported together, then that is quite another
matter.


Even a single function can be useful, since you only need to maintain it 
in one place even if its used in many projects.


But in general a module contains several (hopefully related) functions.
glob.py is a good example.

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] Where is sys.py?

2011-08-22 Thread Lisi
Thanks, Alan.  Very helpful; tho' I probably need to gigest Steven's 
information before I fully digest yours.

On Tuesday 23 August 2011 01:15:52 Alan Gauld wrote:
> So sub-routine comers from the world of assembler programming and was
> adopted by BASIC because BASIC was invented back in the 1960's when most
> folks were used to assembler.

So _that's_ why I understand it.  It is many years since I did any programmimg 
at all, but way back before the ark I did a bit of programming in both Basic 
and machine code.  (And I mean machine code, not assembler.)

Lisi

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