[Tutor] File mode r+

2005-09-24 Thread Shitiz Bansal
Hi,
I want to update a textfile using the r+ file mode.
contents of file:

abcd
efgh
ijkl
mnop
qrst
uvwx
yx12

my scripts is:

file1=open("aa.txt",'r+')
file1.readline()
file1.readline()
file1.write("1234\n")
file1.close()

This should replace the third line with 1234.
However it does nothing.

Moreover the script:

file1=open("aa.txt",'r+')
file1.write("1234\n")
file1.close()

does replace the first line with 1234.

could anyone explain what is happening?

shitiz

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Binary 2 text & text 2 binary

2005-09-24 Thread Pujo Aji
If your symbol are specific it is better to use dictionary.
then if the user give an input you can take character by character and translate into your binary.
This is the code textTobinary:
    mydic = {'A' : "0101", 'B' : "0110", 'C' : "0111"}    strinput = 'ABBC'    result = [mydic[x] for x in strinput_process]    print result 
Cheers,
pujo 
On 9/24/05, Joseph Quigley <[EMAIL PROTECTED]> wrote:
Hi I'm playing with a Binary to text & text to binary converter. I can'tfigure out how to replace the characters (first stage: text to binary).
I thought lists would be the best but I really don't know how to usethem... here's my code:#! /usr/bin/env pythonA = "0101"B = "0110"C = "0111"D = "01000100"
E = "01000101"F = "01000110"G = "01000111"H = "01001000"I = "01001001"J = "01001010"K = "01001011"L = "01001100"
M = "01001101"N = "01001110"O = "0100"P = "0101"Q = "01010001"R = "01010010"S = "01010011"T = "01010100"
U = "01010101"V = "01010110"W = "01010111"X = "01011000"Y = "01011001"Z = "01011010"# SymbolsexclamationPoint = "0010 0001"
hash = "0010 0011"dollar = "001 0100"percent = "0010 0101"_and = "0010 0110"parentheses = "0010 1000"closeParentheses = "0010 1001"comma = "0010 1100"
dash = "0010 1101"period = "0010 1110"underline = "0101 "# Numberszero = "0011">two = "00110010"three = "00110011"
four = "00110100"five = "00110101"six = "00110110"seven = "00110111"eight = "00111000"nine = "00111001"ltra = "a"ltrb = "b"
ltrc = "c"while True:   text = raw_input("Enter text: ")   text = list(text)Thanks,   Joe___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with pi and the math module.

2005-09-24 Thread Pujo Aji
hi,
 
if you use : import math
you can type: diameter * math.pi
 
if you use from math import *
you can type: diameter * pi
 
Cheers,
pujo 
On 9/24/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:

Hi all,
 
I need help with pi and the math module. I had import math at the top of a program, but when it came to diameter*pi, it said that pi was not defined.
 
How do I use it correctly?
 
Thanks,
Nathan Pinno___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Binary 2 text & text 2 binary

2005-09-24 Thread Poor Yorick
Pujo Aji wrote:
> If your symbol are specific it is better to use dictionary.
> then if the user give an input you can take character by character and 
> translate into your binary.
> This is the code textTobinary:
> mydic = {'A' : "0101", 'B' : "0110", 'C' : "0111"}
> strinput = 'ABBC'
> result = [mydic[x] for x in strinput_process]
> print result
>  

You might also want to look at "Number to String in Arbirtrary Base" recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365468

It uses a more innovative approach.

--
Poor Yorick

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


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread Kent Johnson
mailing list wrote:
> Hi all,
> 
> I'm just looking for a quick runthrough on the differences between new
> style classes and the old ones, and how to use the new ones.
> 
> Also, how exactly do you use __slots__? I've got a 6000 object
> collection, and apparently using __slots__ will save memory, but only
> those attributes specified in __slots__ can be set, which suits my
> project fine.

All you have to do is define a __slots__ variable in your class. Its value is a 
list of attribute names. Then instances of your class will only be able to have 
the attributes named in __slots__:

 >>> class foo(object):
 ...   __slots__ = ['x', 'y']
 ...
 >>> f=foo()
 >>> f.x=1
 >>> f.y=2
 >>> f.z=3
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'foo' object has no attribute 'z'

Take a look at
http://www.python.org/2.2.3/descrintro.html (search for __slots__)

Note to the list: Use of __slots__ is generally discouraged, but IIUC this is 
exactly the use case it was designed for so I think it is OK.

Kent

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


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread mailing list
Hi Kent,

>

>  >>> class foo(object):
>  ...   __slots__ = ['x', 'y']
>  ...
>  >>> f=foo()
>  >>> f.x=1
>  >>> f.y=2
>  >>> f.z=3
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'foo' object has no attribute 'z'
>
> Take a look at
> http://www.python.org/2.2.3/descrintro.html (search for __slots__)

Thanks for that. I was tearing my hair out trying to figure out why
despite the usage of __slots__ my instances still had a __dict__, and
then I saw the subclass of object, and sure enough... I'm guessing
that's how you get new style classes.

Quite like what I'm seeing, __slots__ and that property() thing will
allow me to remove all my __setattr__ and __getattr__ methods, which
tend to make things crawl a wee bit.

I was almost considering writing setters/getters to get around the
magic methods, but I grew to dislike them after having used Java, I
got annoyed at having to write setters/getters for every public
variable. Of course, I was using Notepad to write the Java programmes,
and then Eclipse helped me  realise why Java programmers value IDE's
so much, it's that automatic generation of set/gets...

> Note to the list: Use of __slots__ is generally discouraged, but IIUC this is 
> exactly the >use case it was designed for so I think it is OK.

Throwing an error on adding a new attribute is just what I need as the
data I'm reading/writing has a very specific format; instead of using
__setattr__ and checking that the attribute already existed, I can
just let __slots__ do the work.

Out of curiosity, if you're using __slots__ with new style, you no
longer have __dict__. So, where does it stick data?

I was using 'self.__dict__["_created"] = False' to set a flag at the
start of __init__ to stop __setattr__ picking up the attributes being
set from parsed data (and running all my type checks, etc.),  but I
won't need that anymore. I could almost hug property(). :)

All in all, this has been an interesting tour around the inner
workings of a class in Python.
Give it another five years, I might be able to read one of those
metaclass explanations and understand it.


Regards,

Liam Clarke

PS Just for my edification, is there a builtin to determine how much
memory is allocated to an object?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread Kent Johnson
mailing list wrote:
> Hi Kent,
> 
> 
> 
>> >>> class foo(object):
>> ...   __slots__ = ['x', 'y']
>> ...
>> >>> f=foo()
>> >>> f.x=1
>> >>> f.y=2
>> >>> f.z=3
>>Traceback (most recent call last):
>>  File "", line 1, in ?
>>AttributeError: 'foo' object has no attribute 'z'
>>
>>Take a look at
>>http://www.python.org/2.2.3/descrintro.html (search for __slots__)
> 
> 
> Thanks for that. I was tearing my hair out trying to figure out why
> despite the usage of __slots__ my instances still had a __dict__, and
> then I saw the subclass of object, and sure enough... I'm guessing
> that's how you get new style classes.

Yes, exactly. To be precise: A class is a new-style class if its metaclass is 
type 'type' or inherits from type. If you inherit from a new-style class, your 
class will have the same metaclass as the base class and thus be a new-style 
class. The simplest way to do this is to inherit from object.
 
> Quite like what I'm seeing, __slots__ and that property() thing will
> allow me to remove all my __setattr__ and __getattr__ methods, which
> tend to make things crawl a wee bit.

That's exactly what property() is for.
 
> I was almost considering writing setters/getters to get around the
> magic methods, but I grew to dislike them after having used Java, I
> got annoyed at having to write setters/getters for every public
> variable. Of course, I was using Notepad to write the Java programmes,
> and then Eclipse helped me  realise why Java programmers value IDE's
> so much, it's that automatic generation of set/gets...

One of the cool things about properties is that you can start with simple 
attributes and change them later to have behaviour without having to change the 
client code or use getters and setters all the time.
 
> Out of curiosity, if you're using __slots__ with new style, you no
> longer have __dict__. So, where does it stick data?

My understanding is that there are actually 'slots' allocated in the object to 
hold the references to the attribute data, kind of like a C struct. I'm not 
sure about this though.
 
> I was using 'self.__dict__["_created"] = False' to set a flag at the
> start of __init__ to stop __setattr__ picking up the attributes being
> set from parsed data (and running all my type checks, etc.),  but I
> won't need that anymore. I could almost hug property(). :)

You might want to learn more about the whole property mechanism then. 
property() is actually a bit of sugar over a deeper mechanism. Also there is an 
interesting idiom for creating properties using @apply (in Python 2.4) - look 
for Benji York's comment in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698

> 
> All in all, this has been an interesting tour around the inner
> workings of a class in Python.
> Give it another five years, I might be able to read one of those
> metaclass explanations and understand it.

Me too!

Kent
> 
> 
> Regards,
> 
> Liam Clarke
> 
> PS Just for my edification, is there a builtin to determine how much
> memory is allocated to an object?
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

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


[Tutor] Sum of List Elements

2005-09-24 Thread Luke Jordan
Hi All,

I have spent an embarrassingly large amount of time trying to solve what on its face seems like a simple problem.

I have a list of intergers, and I want to assign the sum of the
intergers in the list to a variable. There are only intergers in the
list.

The best I have been able to do so far is to write a function that adds
list[0] and list[1], then list[1] and list [2], etc. Of course, this
isn't what I want.

I'd like to be able to sum a list of any size without having to type list[0]+list[1]

I am totally stumped.

:(

Luke
-- "Whether you're an honest man, or whether you're a thief,
depends on whose solicitor has given me my brief. " - Benjamin Franklin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sum of List Elements

2005-09-24 Thread R. Alan Monroe
> Hi All,

> I have spent an embarrassingly large amount of time trying to solve what on
> its face seems like a simple problem.

> I have a list of intergers, and I want to assign the sum of the intergers in
> the list to a variable. There are only intergers in the list.

> The best I have been able to do so far is to write a function that adds
> list[0] and list[1], then list[1] and list [2], etc. Of course, this isn't
> what I want.

> I'd like to be able to sum a list of any size without having to type
> list[0]+list[1]

total=0
for x in list:
total += x

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


Re: [Tutor] Binary 2 text & text 2 binary

2005-09-24 Thread Joseph Quigley
Hi,

>From: "R. Alan Monroe" <[EMAIL PROTECTED]>
>
>They're easy. Just put stuff in square brackets with commas between.
>
>mycoollist = [1,5,9,3,6,9,2,6]
>mystringlist = ['a', 'u', 'e', 'b', 'd', 'h', 'q', 't']
>  
>
Ah sorry I forgot to say: I know how to print them but that's about it.

>Can you predict what this code will do?
>print mycoollist[0]
>  
>
yes. It will print (edited) [1, 2, 3 ,4 ]
I'll rephrase myself again: I'd like to know where I can find tutorials
for slicing or some help from any of you. However keep on reading and I
think I'll have my answer :-)

>Message: 11
>Date: Sat, 24 Sep 2005 10:42:13 +0200
>From: Pujo Aji <[EMAIL PROTECTED]>
>
>If your symbol are specific it is better to use dictionary.
>  
>
Good Idea! Thanks

>then if the user give an input you can take character by character and
>translate into your binary.
>This is the code textTobinary:
> mydic = {'A' : "0101", 'B' : "0110", 'C' : "0111"}
>strinput = 'ABBC'
>result = [mydic[x] for x in strinput_process]
>print result
>
>  
>
This helps a lot, thank you!


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


Re: [Tutor] Sum of List Elements

2005-09-24 Thread wkranec
how about sum()?

>>> sum(range(30))
435

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


Re: [Tutor] Sum of List Elements

2005-09-24 Thread grouchy
Also, the built in function sum():

total = sum(list)
Which is probably the One Obvious Way since 2.3, if I had to guess.  On 9/24/05, R. Alan Monroe <
[EMAIL PROTECTED]> wrote:> Hi All,> I have spent an embarrassingly large amount of time trying to solve what on
> its face seems like a simple problem.> I have a list of intergers, and I want to assign the sum of the intergers in> the list to a variable. There are only intergers in the list.> The best I have been able to do so far is to write a function that adds
> list[0] and list[1], then list[1] and list [2], etc. Of course, this isn't> what I want.> I'd like to be able to sum a list of any size without having to type> list[0]+list[1]

total=0for x in list:total += x___Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] File mode r+

2005-09-24 Thread bob
At 01:11 AM 9/24/2005, Shitiz Bansal wrote:
>Hi,
>I want to update a textfile using the r+ file mode.
>contents of file:
>
>abcd
>efgh
>ijkl
>mnop
>qrst
>uvwx
>yx12
>
>my scripts is:
>
>file1=open("aa.txt",'r+')

Instead of readline, use skip to position the file to where you want to 
overwrite it.
file1.seek(10)

>file1.readline()
>file1.readline()
>file1.write("1234\n")
>file1.close()
>
>This should replace the third line with 1234.
>However it does nothing.
>
>Moreover the script:
>
>file1=open("aa.txt",'r+')
>file1.write("1234\n")
>file1.close()
>
>does replace the first line with 1234.
>
>could anyone explain what is happening?
>
>shitiz
>
>__
>Do You Yahoo!?
>Tired of spam?  Yahoo! Mail has the best spam protection around
>http://mail.yahoo.com
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Stupid newbie question

2005-09-24 Thread grouchy
As long as you are using IDLE, why not let it handle indentation for you?  This could very well be a dumb question, and if it is, well, excuse me :)On 9/23/05, 
Valone, Toren W. <[EMAIL PROTECTED]> wrote:
I am trying to noodle thru classes with python and I built the followingclassimport timeclass startremail:def __init__(self): remailfile = open('U:\Bounce20.txt', 'r') #future
address/file from outlook resendfile = open('resend.txt', 'w')  #currently thesefiles are in Python24 EmailReport = open('erprt.txt', 'w')  #Report of bademails etc
 fromaddr='[EMAIL PROTECTED]' #set fromadd to aconstant null_recepient_count = 0 date_received = "" date_email_generated = ""
 Error_050 = "" Error_501 = "" Current_Date = time.ctime(time.time()) month = Current_Date[4:8] day = Current_Date[8:10] print month def getday(self):
 return self.day def Read(self,line): line = remailfile.readline()  #primer read return lineI fire up IDLE and then do thisfrom startremail import *
x = startremail()print x.getday()I get the following returnNameError: name 'getday' is not defined___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sum of List Elements

2005-09-24 Thread bob
At 08:11 AM 9/24/2005, Luke Jordan wrote:
>Hi All,
>
>I have spent an embarrassingly large amount of time trying to solve what 
>on its face seems like a simple problem.
>
>I have a list of intergers, and I want to assign the sum of the intergers 
>in the list to a variable. There are only intergers in the list.

In addition to the other solutions there is the (more generic?) use of the 
operator module and reduce function:

import operator
reduce(operator.add, (1,2,3))

Explore operator to see what other functions you can use.

Also there are the array handling modules such as numarray.

You can also define your own classes based on list and write methods to do 
these operations. 

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


Re: [Tutor] Sum of List Elements

2005-09-24 Thread Luke Jordan
Thanks for the help everyone, for answering a simple question and pointing me toward more resources.On 9/24/05, bob <
[EMAIL PROTECTED]> wrote:At 08:11 AM 9/24/2005, Luke Jordan wrote:>Hi All,
>>I have spent an embarrassingly large amount of time trying to solve what>on its face seems like a simple problem.>>I have a list of intergers, and I want to assign the sum of the intergers
>in the list to a variable. There are only intergers in the list.In addition to the other solutions there is the (more generic?) use of theoperator module and reduce function:import operator
reduce(operator.add, (1,2,3))Explore operator to see what other functions you can use.Also there are the array handling modules such as numarray.You can also define your own classes based on list and write methods to do
these operations.-- "Whether
you're an honest man, or whether you're a thief, depends on whose
solicitor has given me my brief. " - Benjamin Franklin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File mode r+

2005-09-24 Thread Shitiz Bansal

Hi,
How do i proceed if i am not sure about the number of characters in the fist two lines and want to write in the third line.is there a way to skip two lines and write on the third??
Also could anyone explain why the readline() did not work. according to what i understand it should.
 
shitizbob <[EMAIL PROTECTED]> wrote:

At 01:11 AM 9/24/2005, Shitiz Bansal wrote:>Hi,>I want to update a textfile using the r+ file mode.>contents of file:>>abcd>efgh>ijkl>mnop>qrst>uvwx>yx12>>my scripts is:>>file1=open("aa.txt",'r+')>>Instead of readline, use skip to position the file to where you want to >>overwrite it.>>file1.seek(10)
>file1.readline()>file1.readline()>file1.write("1234\n")>file1.close()>>This should replace the third line with 1234.>However it does nothing.>>Moreover the script:>>file1=open("aa.txt",'r+')>file1.write("1234\n")>file1.close()>>does replace the first line with 1234.>>could anyone explain what is happening?>>shitiz>>__>Do You Yahoo!?>Tired of spam? Yahoo! Mail has the best spam protection around>http://mail.yahoo.com>___>Tutor maillist - Tutor@python.org>http://mail.python.org/mailman/listinfo/tutor
		Yahoo! for Good 
Click here to donate to the Hurricane Katrina relief effort. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread Liam Clarke
Hi,


> You might want to learn more about the whole property mechanism then. 
> property() is actually a bit of sugar over a deeper mechanism. Also there is 
> an interesting idiom for creating properties using @apply (in Python 2.4) - 
> look for Benji York's comment in this recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698

Thanks Kent. Just looking at that above recipe, I'm not too sure how
the @ decorators work.
>From what I understand, it defines would turn apply() into a function
that returns the various get/sets?

Also found something interesting with property(), if it's called in
__init__ you get
>>> a.a


whereas called outside __init__ it works normally.

This is a hassle for me because I'm a lazy typist, so I've been using
setattr() to pull attribute names out of a list. And the first
argument setattr() requires is an object, and self doesn't work
outside of a method, and using the class name leads to no attribute
being set.

Hmm, may have to learn even more about classes and their internals.

Regards,

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


[Tutor] (no subject)

2005-09-24 Thread Goofball223
Hello

How would I get the following program to accept inputs of exam scores from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and F being everything less than 60?

import string

def main():


    scores = ["F", "D", "C", "B", "A"]
    g = input("Enter a score number (0-100): ")

    print "The score of your exam is", scores [g-0] + "."


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


[Tutor] printing an acronym

2005-09-24 Thread andrade1
Hello

How could I get the following to print out an acronym for each phrase
entered such as if I entered random access memory it word print out RAM?

import string

def main():


phrase = (raw_input("Please enter a phrase:"))

acr1 = string.split(phrase)


acr2 = string.capwords(phrase)


acr3 = acr2[0]

print"",acr3

main()

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


Re: [Tutor] printing an acronym

2005-09-24 Thread R. Alan Monroe
> Hello

> How could I get the following to print out an acronym for each phrase
> entered such as if I entered random access memory it word print out RAM?

> import string

> def main():


> phrase = (raw_input("Please enter a phrase:"))

> acr1 = string.split(phrase)


> acr2 = string.capwords(phrase)


> acr3 = acr2[0]

> print"",acr3

> main()

What does it currently print?

The typical way would be to use a for loop on acr1.

Alan

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


Re: [Tutor] (no subject)

2005-09-24 Thread bob


At 03:29 PM 9/24/2005, [EMAIL PROTECTED] wrote:
Hello

How would I get the following program to accept inputs of exam scores
from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being
69-60, and F being everything less than 60? 
Many solutions are available. One could use an if statement:
if g >= 90: s = 'A'
elif g >= 80: s = 'B'
...
else: g = 'F' 
although that can be hard to 
maintain.
Or associate the lower limit with the data and search using a
loop:
scores = [("A",90), ("B",80), ("C".70),
("D",60),("F",0) ] 
for letter, number in scores:
    if g >= number:break
print "The score of your exam is", letter
This separates the data from the program structure and becomes much
easier to maintain / extend, apply to new situation.
If you are using a database then you could store these value pairs in a
table and use SQL to retrieve the desired letter.
When the number ranges have a nice progression, you can reduce the number
to an index:
print "The score of your exam is",
"FEDCBAA"[g/10] # this is simpler code but harder to
read/maintain.
Or - knowing that chr(65) = "A", chr(66) = "B" you
could convert the number to be in the range 65..70 and use 
chr()
import string

You do not refer to the string module, so there is no need to import it.
Also be ware that it will eventually go away.

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


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread Liam Clarke
Ooer,

Well, I got setattr() and property() working together nicely, but with
a weird side effect.

class Strange(object):
def getA(um, self):
print "What is", um
return self.__a

def setA(um, self, value):
print um, "turns up here as well."
self.__a = value

def __init__(self):
setattr(Strange, "a", property(self.getA, self.setA))
self.a = 20

>>> c = Strange()
<__main__.Strange object at 0x01166290> turns up here as well.
>>> print c.a
What is <__main__.Strange object at 0x01166290>
20
>>> c
<__main__.Strange object at 0x01166290>

To my uneducated eye, it looks like it's passing self twice! Returning
um.__a works exactly the same as self.__a!

I'm getting the feelin I may need to venture into comp.lang.Python
with this sort of stuff.

Interesting.

Liam Clarke

On 9/25/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Hi,
>
>
> > You might want to learn more about the whole property mechanism then. 
> > property() is actually a bit of sugar over a deeper mechanism. Also there 
> > is an interesting idiom for creating properties using @apply (in Python 
> > 2.4) - look for Benji York's comment in this recipe:
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
>
> Thanks Kent. Just looking at that above recipe, I'm not too sure how
> the @ decorators work.
> From what I understand, it defines would turn apply() into a function
> that returns the various get/sets?
>
> Also found something interesting with property(), if it's called in
> __init__ you get
> >>> a.a
> 
>
> whereas called outside __init__ it works normally.
>
> This is a hassle for me because I'm a lazy typist, so I've been using
> setattr() to pull attribute names out of a list. And the first
> argument setattr() requires is an object, and self doesn't work
> outside of a method, and using the class name leads to no attribute
> being set.
>
> Hmm, may have to learn even more about classes and their internals.
>
> Regards,
>
> Liam Clarke
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread Kent Johnson
Liam Clarke wrote:
>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
> 
> 
> Thanks Kent. Just looking at that above recipe, I'm not too sure how
> the @ decorators work.
>>From what I understand, it defines would turn apply() into a function
> that returns the various get/sets?

OK, lets pick it apart a bit. Here is the recipe for defining a property:
class Example(object):
@apply
def myattr():
doc = """This is the doc string."""

def fget(self):
return self._value

def fset(self, value):
self._value = value

def fdel(self):
del self._value

return property(**locals())

Looking at myattr(), it defines the four attributes that make a property - doc, 
fget, fset and fdel. So at the end of myattr(), locals() is a dictionary 
containing these four attributes. Then it calls property() and passes it 
locals() as keyword arguments. So the last line is the same as return 
property(doc=doc, fget=fget, fset=fset, fdel=fdel) which creates a normal 
property.

OK, now what does the @apply do? Well, it's a decorator, and in general
@some_decorator
def myfunc():
  # etc

means the same thing as
def myfunc():
  # etc
myfunc = some_decorator(myfunc)

In other words the decorator is called with the function as an argument, and 
the return value of the function is bound to the name of the original function. 
So we have to know what apply(myattr) does. Actually, it just calls myattr(). 
So the net result is
myattr = myattr() i.e.
myattr = property(doc=doc, fget=fget, fset=fset, fdel=fdel)
which is what you would have done any way if you weren't trying to be so clever.

What does this recipe buy you? It puts the property function definitions into a 
separate namespace so they are not accessible as member functions, and it lets 
you reuse the names for them instead of having to invent new ones each time.
> 
> Also found something interesting with property(), if it's called in
> __init__ you get
> 
a.a
> 
> 
> 
> whereas called outside __init__ it works normally.

Are you assigning the property to self or to the class? It might work if you 
assign to the class. But you will be recreating the properties for every 
instance.
> 
> This is a hassle for me because I'm a lazy typist, so I've been using
> setattr() to pull attribute names out of a list. And the first
> argument setattr() requires is an object, and self doesn't work
> outside of a method, and using the class name leads to no attribute
> being set.

I don't understand this at all, can you give an example?
> 
> Hmm, may have to learn even more about classes and their internals.

Yeah, it sounds like maybe a case for a metaclass.

Kent

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

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


Re: [Tutor] Using new style classes and __slots__

2005-09-24 Thread Kent Johnson
Your method signatures are off. Should be
def getA(self):
def setA(self, value)

So when you write self.a = 20 you are passing self as the um parameter. 
Actually I don't know why you don't get an exception for passing too many 
arguments?

And you don't need setattr, just write
Strange.a = property(...)

Oh wait, I get it - you are passing bound methods to property(). So um is bound 
to the instance when you access self.getA. Use Strange.getA instead of 
self.getA, then use the normal signatures.

But I don't get why you are doing this at all? What does it buy you over the 
standard form of

class Normal(object):
def getA(self):
return self.__a

def setA(self, value):
self.__a = value

a = property(getA, setA)

def __init__(self):
self.a = 20

One more note below.

Kent

Liam Clarke wrote:
> Ooer,
> 
> Well, I got setattr() and property() working together nicely, but with
> a weird side effect.
> 
> class Strange(object):
> def getA(um, self): 
> print "What is", um
> return self.__a
> 
> def setA(um, self, value):
> print um, "turns up here as well."
> self.__a = value
> 
> def __init__(self):
> setattr(Strange, "a", property(self.getA, self.setA))
> self.a = 20
> 
> 
c = Strange()
> 
> <__main__.Strange object at 0x01166290> turns up here as well.
> 
print c.a
> 
> What is <__main__.Strange object at 0x01166290>
> 20
> 
c
> 
> <__main__.Strange object at 0x01166290>
> 
> To my uneducated eye, it looks like it's passing self twice! Returning
> um.__a works exactly the same as self.__a!

It is passing self twice, because you are using a bound method as the property 
method rather than an unbound method.

> 
> I'm getting the feelin I may need to venture into comp.lang.Python
> with this sort of stuff.
> 
> Interesting.
> 
> Liam Clarke
> 
> On 9/25/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> 
>>Hi,
>>
>>
>>
>>>You might want to learn more about the whole property mechanism then. 
>>>property() is actually a bit of sugar over a deeper mechanism. Also there is 
>>>an interesting idiom for creating properties using @apply (in Python 2.4) - 
>>>look for Benji York's comment in this recipe:
>>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
>>
>>Thanks Kent. Just looking at that above recipe, I'm not too sure how
>>the @ decorators work.
>>From what I understand, it defines would turn apply() into a function
>>that returns the various get/sets?
>>
>>Also found something interesting with property(), if it's called in
>>__init__ you get
>>
>a.a
>>
>>
>>
>>whereas called outside __init__ it works normally.
>>
>>This is a hassle for me because I'm a lazy typist, so I've been using
>>setattr() to pull attribute names out of a list. And the first
>>argument setattr() requires is an object, and self doesn't work
>>outside of a method, and using the class name leads to no attribute
>>being set.
>>
>>Hmm, may have to learn even more about classes and their internals.
>>
>>Regards,
>>
>>Liam Clarke
>>
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

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


[Tutor] creating strings

2005-09-24 Thread Goofball223
Hello

How would I get the following program to accept inputs of exam scores from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and F being everything less than 60?

import string

def main():


   scores = ["F", "D", "C", "B", "A"]
   g = input("Enter a score number (0-100): ")

   print "The score of your exam is", scores [g-0] + "."


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


Re: [Tutor] (no subject)

2005-09-24 Thread Liam Clarke
I'd also like to mention that input() is bad, as you can enter Python
statements and it'll execute them. For instance, entering "sys.exit()"
would cause your programme to try and call sys.exit(), which if the
sys module had been imported, would quit.

You can do far more malevolent things than that, of course.

Best to use

g = int(raw_input("Enter a score number (0-100): "))

Come Python 3.0, raw_input and input are to both get the boot, I
believe, in favour of sys.stdin.read()
On 9/25/05, bob <[EMAIL PROTECTED]> wrote:
>  At 03:29 PM 9/24/2005, [EMAIL PROTECTED] wrote:
>
> Hello
>
>  How would I get the following program to accept inputs of exam scores from
> 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and
> F being everything less than 60?
>  Many solutions are available. One could use an if statement:
>
>  if g >= 90: s = 'A'
>  elif g >= 80: s = 'B'
>  ...
>  else: g = 'F'
>
>  although that can be hard to maintain.
>
>  Or associate the lower limit with the data and search using a loop:
>
>  scores = [("A",90), ("B",80), ("C".70), ("D",60),("F",0) ]
>  for letter, number in scores:
>  if g >= number:break
>  print "The score of your exam is", letter
>
>  This separates the data from the program structure and becomes much easier
> to maintain / extend, apply to new situation.
>
>  If you are using a database then you could store these value pairs in a
> table and use SQL to retrieve the desired letter.
>
>  When the number ranges have a nice progression, you can reduce the number
> to an index:
>
>  print "The score of your exam is", "FEDCBAA"[g/10] # this is simpler
> code but harder to read/maintain.
>
>  Or - knowing that chr(65) = "A", chr(66) = "B" you could convert the number
> to be in the range 65..70 and use chr()
>
>
> import string
>  You do not refer to the string module, so there is no need to import it.
> Also be ware that it will eventually go away.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] numbers from a name

2005-09-24 Thread Goofball223
Hello

with the following program I would like it to be able to take a person's name  and then assign values to each letter and come up with a sum of all the letters in the name. for example if I entered bob. i would like the program to be able to print bob and then print the total of bob which would be 2 + 15 + 2 = 18. 





import string

def main():
    value = (raw_input("Please enter your first name"))

 table = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 6, 'g' : 7, 'h' : 8, 'i' : 9, 'j' : 10, 'k' : 11, 'l' : 12, 'm' : 13, 'n' : 14, 'o' : 15, 'p' : 16, 'q' : 17, 'r' : 18, 's' : 19, 't' : 20, 'u' : 21, 'v' : 22, 'w' : 23, 'x' : 24, 'y' : 25, 'z' : 26}


 total = 0
 name = list(name)

 for string in name:
 total += table[string.lower()]
 print "The total of your name is:", total

main()

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


Re: [Tutor] numbers from a name

2005-09-24 Thread ZIYAD A. M. AL-BATLY
On Sat, 2005-09-24 at 23:50 -0400, [EMAIL PROTECTED] wrote:
> Hello
Hi Goofball...

>
> with the following program I would like it to be able to take a
> person's name  and then assign values to each letter and come up with
> a sum of all the letters in the name. for example if I entered bob. i
> would like the program to be able to print bob and then print the
> total of bob which would be 2 + 15 + 2 = 18.
>
It should be 19, not 18.

> import string 
You don't need the "string" module for something this simple.  Just
read.

> def main(): 
>value = (raw_input("Please enter your first name"))
Why the parenthesis?  This is better:
value = raw_input("Please enter your first name: ")

Also, after that you can convert the whole string to lower letters in
one step:
value = value.lower()

A good resource for information about Python's built-ins and modules is
to start the Python shell and type "help(something)", where "something"
is what you want more info about.

In the above example, "raw_input" will return an object of type "str".
Type "help(str)" and see a lot of things you could do to/with "str"
objects!  (By the way, I found that "raw_input" returns "str" by typing
"help(raw_input) in Python! :) )

> table = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 6,
> 'g' : 7, 'h' : 8, 'i' : 9, 'j' : 10, 'k' : 11, 'l' : 12, 'm' : 13,
> 'n' : 14, 'o' : 15, 'p' : 16, 'q' : 17, 'r' : 18, 's' : 19, 't' : 20,
> 'u' : 21, 'v' : 22, 'w' : 23, 'x' : 24, 'y' : 25, 'z' : 26}
You could write a loop to create the "table" for you.  Though, It will
be slower than the above method and will consume more system resources.
But it will be much easier on you.   (A Real Programmer is a lazy one!:)
Just kidding!)

>
> total = 0
> name = list(name)
What's "name" for?  Also, "name" never used before!  Did you mean
"name=list(value)"?  But I don't see how's that going to help.
> 
> for string in name:
> total += table[string.lower()]
> print "The total of your name is:", total 
"string" is the name of a module!  You can't use it here _if_ you
imported that module.  And as mentioned above, what's "name"?

Try this:
for x in value:
total += table[x]
print "The total of your name is:", total

"x" will iterate for each item (in this case, letter) in "value" which
holds the lowered case input.  "table" have each letter assigned to a
number.  "table[x]" will look-up "table" and _return_ the _number_
assigned to the letter that is held in "x".

If you didn't understand this just ask here again and many well be glad
to help.


> main() 


Ziyad.

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


Re: [Tutor] numbers from a name

2005-09-24 Thread Goofball223
How could I change the program to accept something like: John Bob Zelle Python or Kip Rada?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing an acronym

2005-09-24 Thread Danny Yoo


On Sat, 24 Sep 2005 [EMAIL PROTECTED] wrote:

> How could I get the following to print out an acronym for each phrase
> entered such as if I entered random access memory it word print out RAM?


Hello,

Just out of curiosity, are you already familiar with Python's "lists"?

If so, then you might want to try the slightly easier problem of pulling
out acronyms out of a list of words.  Extracting an acronym out of a list
like:

["International", "Business", "Machines"]

==> "IBM"

is not too bad, and is one step toward doing the original problem on the
phrase "International Business Machines".


Tutorials like:

http://www.freenetpages.co.uk/hp/alan.gauld/tutseq2.htm

and the other tutorials on:

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

should talk about lists.  Please feel free to ask questions here!

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


Re: [Tutor] (no subject)

2005-09-24 Thread Danny Yoo


On Sat, 24 Sep 2005 [EMAIL PROTECTED] wrote:


> How would I get the following program to accept inputs of exam scores
> from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being
> 69-60, and F being everything less than 60?

Hello,

Are you familiar with "if/elif/else"?  These "control-flow"  statements
should help you express the above grading idea fairly straightforwardly.

For experienced programmers, there is a module in the Standard Library
that does pretty much what you want.  I'll link to it below, but you
probably won't want to use it: learn to use if/elif/else first; I'd hate
to stunt your Python learning.  *grin*









Link for experienced programmers:

http://www.python.org/doc/lib/bisect-example.html

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