Re: [Tutor] how to unique the string

2011-10-24 Thread Peter Otten
lina wrote:

> But I am getting confused later:
> 
> def translate_process(dictionary,tobetranslatedfile):
> results=[]
> unique={}
> for line in open(tobetranslatedfile,"r"):
> tobetranslatedparts=line.strip().split()
> results.append(dictionary[tobetranslatedparts[2]])

> unique=Counter(results)
> with open(base+OUTPUTFILEEXT,"w") as f:
> for residue, numbers in unique.items():
> print(residue,numbers,file=f)

As Dave says, the above four lines should run only once, outside the for-
loop. 

Here's a way to avoid the intermediate results list. As a bonus I'm removing 
access to the `base` global variable:

def change_ext(name, new_ext):
"""
>>> change_ext("/deep/blue.eyes", ".c")
'/deep/blue.c'
"""
return os.path.splitext(name)[0] + new_ext

def translate_process(dictionary, tobetranslatedfile):
with open(tobetranslatedfile, "r") as f:
results = (dictionary[line.split()[2]] for line in f)
unique = Counter(results)

with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out:
for residue, numbers in unique.items():
print(residue, numbers, file=out)


> it still the same in the OUTPUTFILE as before,
> 
>  $ more atom-pair_6.txt
> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5}

Unlikely. Verify that you are running the correct script and looking into 
the right output file.


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


Re: [Tutor] how to unique the string

2011-10-24 Thread lina
On Mon, Oct 24, 2011 at 3:24 PM, Peter Otten <__pete...@web.de> wrote:
> lina wrote:
>
>> But I am getting confused later:
>>
>> def translate_process(dictionary,tobetranslatedfile):
>>     results=[]
>>     unique={}
>>     for line in open(tobetranslatedfile,"r"):
>>         tobetranslatedparts=line.strip().split()
>>         results.append(dictionary[tobetranslatedparts[2]])
>
>>         unique=Counter(results)
>>         with open(base+OUTPUTFILEEXT,"w") as f:
>>             for residue, numbers in unique.items():
>>                 print(residue,numbers,file=f)
>
> As Dave says, the above four lines should run only once, outside the for-
> loop.
>
> Here's a way to avoid the intermediate results list. As a bonus I'm removing
> access to the `base` global variable:
>
> def change_ext(name, new_ext):
>    """
>    >>> change_ext("/deep/blue.eyes", ".c")
>    '/deep/blue.c'
>    """
>    return os.path.splitext(name)[0] + new_ext
>
> def translate_process(dictionary, tobetranslatedfile):
>    with open(tobetranslatedfile, "r") as f:
>        results = (dictionary[line.split()[2]] for line in f)
>        unique = Counter(results)
>
>    with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out:
>        for residue, numbers in unique.items():
>            print(residue, numbers, file=out)
>
>
>> it still the same in the OUTPUTFILE as before,
>>
>>  $ more atom-pair_6.txt
>> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5}
>
> Unlikely. Verify that you are running the correct script and looking into
> the right output file.

Thanks,
print(residue,numbers,"\n",file=f)
achieve this.
62PHE 10

34LEU 37

43ASP 6


but seems the \n added one more line,
>
>
> ___
> 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] how to unique the string

2011-10-24 Thread lina

>>
>> def translate_process(dictionary,tobetranslatedfile):
>>     results=[]
>>     unique={}
>>     for line in open(tobetranslatedfile,"r"):
>>         tobetranslatedparts=line.strip().split()
>>         results.append(dictionary[tobetranslatedparts[2]])
>>         unique=Counter(results)
>>         with open(base+OUTPUTFILEEXT,"w") as f:
>
> Every time you do this, you're truncating the file.  It'd be better to open
> the file outside the for-line loop, and just use the file object in the
> loop.

 Before I did not understand well, until I read Peter's following post.

Thanks,

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


Re: [Tutor] how to unique the string

2011-10-24 Thread lina
On Mon, Oct 24, 2011 at 3:24 PM, Peter Otten <__pete...@web.de> wrote:
> lina wrote:
>
>> But I am getting confused later:
>>
>> def translate_process(dictionary,tobetranslatedfile):
>>     results=[]
>>     unique={}
>>     for line in open(tobetranslatedfile,"r"):
>>         tobetranslatedparts=line.strip().split()
>>         results.append(dictionary[tobetranslatedparts[2]])
>
>>         unique=Counter(results)
>>         with open(base+OUTPUTFILEEXT,"w") as f:
>>             for residue, numbers in unique.items():
>>                 print(residue,numbers,file=f)
>
> As Dave says, the above four lines should run only once, outside the for-
> loop.
>
> Here's a way to avoid the intermediate results list. As a bonus I'm removing
> access to the `base` global variable:
>
> def change_ext(name, new_ext):
>    """
>    >>> change_ext("/deep/blue.eyes", ".c")
>    '/deep/blue.c'
>    """
>    return os.path.splitext(name)[0] + new_ext
>
> def translate_process(dictionary, tobetranslatedfile):
>    with open(tobetranslatedfile, "r") as f:
>        results = (dictionary[line.split()[2]] for line in f)
>        unique = Counter(results)
>
>    with open(change_ext(tobetranslatedfile, OUTPUTFILEEXT), "w") as out:
>        for residue, numbers in unique.items():
>            print(residue, numbers, file=out)

Now work as expected. concise than before.

Thanks,
>
>
>> it still the same in the OUTPUTFILE as before,
>>
>>  $ more atom-pair_6.txt
>> {'26SER': 2, '16LYS': 1, '83ILE': 2, '70LYS': 6, '55HIS': 5}
>
> Unlikely. Verify that you are running the correct script and looking into
> the right output file.
>
>
> ___
> 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] Simple Question On A Method (in subclass)

2011-10-24 Thread Alan Gauld

On 24/10/11 04:08, Chris Kavanagh wrote:


Thanks so much for the help Alan. . .I'm not trying to beat this
question into the ground, LOL, but let me see if I can ask it a better way.


Marc has already given a good answer, but I'll try a slightly different 
approach to the same thing The differences are purely philosophical :-)



So we have {member.tell} as the last line of code. So trying to
understand this piece of code, {member} the variable is considered an
object?


Almost.

member is an object because it is an instance of a class.
We created instances of Teacher and Student (t and s) and put them in a 
list (members) with this code:


t = Teacher('Mrs. Shrividya', 40, 3)
s = Student('Swaroop', 22, 75)
members = [t, s]

Thus for member in members takes each object in the list and assigns it 
to member.


We can read {for member in members} as

"Let member take on, in turn, each value in the collection members"

And making it more explicit with a while loop:

index = 0
while index < len(members):
member = members[index]
member.tell()
index += 1

> Therefore we can combine it with a function {tell()} using dot
> notation?? Is this correct??? I haven't seen anything but an
> object combined with a function using dot notation.

dot notation is how we access anything that is defined inside the class 
definition. In this case there are only the __init__() and tell() 
methods but there could be data attributes too. Furthermore we can add 
data attributes to the objects by using the self parameter, as is done 
in __init__() So we end up with the instance containing the attributes 
defined at the class level (including those of its superclass) plus any 
added by the __init__() method which is called when the object is 
created (or instantiated). So for Teacher the attributes will be:


__init__()
tell()
name   - from SchoolMember.__init__()
age- ditto
salary - from Teacher.__init__()

So we could have accessed any of those for the first iteration of the 
loop because member was a Teacher instance (t) using:


member.tell, member.name, member.age, member.salary

But the last one would have broken for the second object in the list 
since it was a student, which doesn't have a salary. So when dealing 
with a list of objects we have to restrict the access via dot notation 
to those attributes that are common to all objects in the collection - 
usually the ones defined in the super class.


Python doesn't care whether the attributes we access are data or 
functions because in Python everything is an "object" (see Marc's post)
But by putting parentheses after the object name Python treats the named 
object as a function (specifically a "callable" object)


You can see this diffence at work in the interpreter if you
type this:

>>> def f():
...   return "Called f"
...
>>> print f

>>> print f()
Called f

See the difference the () made? Without it we print the function object 
called f. With it we print the result of calling the function f.
Thats quite a subtle concept and usually hard for beginners to grasp but 
it is a very powerful concept and you will find it being used in

more advanced programs, especially GUI development.

>  So I'm trying to figure out how we can

combine the variable {member} with the function {tell}. Hope this
question makes sense to you, LOL. Thanks again.


How we combine it is done inside Python as part of the magic of classes 
and instantiation. Basically you can call any function defined inside a 
class and Python will automatically assign the first parameter of that 
function to the object instace that you are referencing at the time.


Thus when we do

for member in members:
   member.tell()

Python recognises that first time round member refers to the object t 
which is an instanmce of Teacher. It then calls the tell() method within 
the Teacher class definition and assigns t as the self parameter.

We could write it explicitly as:

Teacher.tell(member)  # where member is t

On the second time round member is assigned to s and Python recognizes 
that s in an instance of Student. So it calls Student.tell(member) where 
member is s.


The member.tell() notation is just a convenient way for us to write it
and allows Python to do the hard work of figuring out what kind of 
object member is at any given time.


[Aside: In true OOP speak we describe the process as "sending a message 
to the object. Thus member.tell() sends the message "tell" to the object 
"member" and the OOP framework invokes the corresponding method tell() 
in the corresponding class. In some OOP languages you can use different 
names for the messages and corresponding methods but in Python they are 
the same so we just talk about calling the method.]


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/

Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-24 Thread lina


a quick Q: Every time call the method, need go through the __initi__( ) part?

Thanks, I attached the one I used to practice fast-typing:

#!/usr/bin/python3


class SchoolMember:
'''Represents any school members.'''

def __init__(self,name,age):
self.name = name
self.age = age
print("Initialized School Memeber: ", self.name)

def tell(self):
'''Tell my details.'''
print("Name:", self.name, "Age: ", self.age)

class Teacher(SchoolMember):
'''Represents a Teacher'''

def __init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary = salary
print("Initialized Teacher", self.name)

def tell(self):
SchoolMember.tell(self)
print("Salary:", self.salary)

class Student(SchoolMember):
'''Represent a student.'''

def __init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks = marks
print("Initialized Student:", self.name)

def tell(self):
SchoolMember.tell(self)
print("Marks: ", self.marks)

t = Teacher('Mrs. Shrividya',40,3)
s = Student('Swaroop',22,75)

print()

members=[t,s]
for member in members:
member.tell()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-24 Thread Chris Kavanagh



On 10/24/2011 4:40 AM, Alan Gauld wrote:

On 24/10/11 04:08, Chris Kavanagh wrote:


Thanks so much for the help Alan. . .I'm not trying to beat this
question into the ground, LOL, but let me see if I can ask it a better
way.


Marc has already given a good answer, but I'll try a slightly different
approach to the same thing The differences are purely philosophical :-)


So we have {member.tell} as the last line of code. So trying to
understand this piece of code, {member} the variable is considered an
object?


Almost.

member is an object because it is an instance of a class.
We created instances of Teacher and Student (t and s) and put them in a
list (members) with this code:

t = Teacher('Mrs. Shrividya', 40, 3)
s = Student('Swaroop', 22, 75)
members = [t, s]

Thus for member in members takes each object in the list and assigns it
to member.

We can read {for member in members} as

"Let member take on, in turn, each value in the collection members"

And making it more explicit with a while loop:

index = 0
while index < len(members):
member = members[index]
member.tell()
index += 1

 > Therefore we can combine it with a function {tell()} using dot
 > notation?? Is this correct??? I haven't seen anything but an
 > object combined with a function using dot notation.

dot notation is how we access anything that is defined inside the class
definition. In this case there are only the __init__() and tell()
methods but there could be data attributes too. Furthermore we can add
data attributes to the objects by using the self parameter, as is done
in __init__() So we end up with the instance containing the attributes
defined at the class level (including those of its superclass) plus any
added by the __init__() method which is called when the object is
created (or instantiated). So for Teacher the attributes will be:

__init__()
tell()
name - from SchoolMember.__init__()
age - ditto
salary - from Teacher.__init__()

So we could have accessed any of those for the first iteration of the
loop because member was a Teacher instance (t) using:

member.tell, member.name, member.age, member.salary

But the last one would have broken for the second object in the list
since it was a student, which doesn't have a salary. So when dealing
with a list of objects we have to restrict the access via dot notation
to those attributes that are common to all objects in the collection -
usually the ones defined in the super class.

Python doesn't care whether the attributes we access are data or
functions because in Python everything is an "object" (see Marc's post)
But by putting parentheses after the object name Python treats the named
object as a function (specifically a "callable" object)

You can see this diffence at work in the interpreter if you
type this:

 >>> def f():
... return "Called f"
...
 >>> print f

 >>> print f()
Called f

See the difference the () made? Without it we print the function object
called f. With it we print the result of calling the function f.
Thats quite a subtle concept and usually hard for beginners to grasp but
it is a very powerful concept and you will find it being used in
more advanced programs, especially GUI development.

 > So I'm trying to figure out how we can

combine the variable {member} with the function {tell}. Hope this
question makes sense to you, LOL. Thanks again.


How we combine it is done inside Python as part of the magic of classes
and instantiation. Basically you can call any function defined inside a
class and Python will automatically assign the first parameter of that
function to the object instace that you are referencing at the time.

Thus when we do

for member in members:
member.tell()

Python recognises that first time round member refers to the object t
which is an instanmce of Teacher. It then calls the tell() method within
the Teacher class definition and assigns t as the self parameter.
We could write it explicitly as:

Teacher.tell(member) # where member is t

On the second time round member is assigned to s and Python recognizes
that s in an instance of Student. So it calls Student.tell(member) where
member is s.

The member.tell() notation is just a convenient way for us to write it
and allows Python to do the hard work of figuring out what kind of
object member is at any given time.

[Aside: In true OOP speak we describe the process as "sending a message
to the object. Thus member.tell() sends the message "tell" to the object
"member" and the OOP framework invokes the corresponding method tell()
in the corresponding class. In some OOP languages you can use different
names for the messages and corresponding methods but in Python they are
the same so we just talk about calling the method.]

HTH,

Yes, both of you gave great answers. I just couldn't get it straight in 
my head for some reason. And I do get it now. I just wasn't seeing 
{member} as an instance of a class. I guess because I'm used to seeing 
simple straightforward examples of classes 

Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-24 Thread Wayne Werner
On Sun, Oct 23, 2011 at 11:06 PM, Marc Tompkins wrote:

> Things to remember:
> -you can get a value from a method, but you can't assign to it:
> variable = object.method()
> but NOT
> object.method() = variable
>

As a slight aside, you _can_ assign to the method name:

object.method = variable #object.method is now whatever variable was

I'm not aware of any valid reason to do this, that is to say I don't know of
anything that you could do this way that you couldn't do another more
readable/maintainable way.

But I could be wrong!

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


[Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread Praveen Singh
In Dictionary-
How to print corresponding keys if the values of dictionary is given??

-d={'a':1,'b':2,'c':3}
-i can print the corresponding values by using get() method-
- d.get('a')
-1

What if i have to print reverse???
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread Raúl Cumplido
Hi,

Keys are unique in a dictionaire but values aren't. What do you want to
print if you have the next dictionaire:

dict = {'a' : 1, 'b' : 1}

If you are using python 2.7 you can use dictionary comprehensions to swap
keys for values:

>>> d={'a':1,'b':2,'c':3}
>>> new_dict = {v : k for k,v in d.iteritems()}
>>> new_dict
{1: 'a', 2: 'b', 3: 'c'}

but if you're values are repeated you will loose some keys:
>>> dict = {'a' : 1, 'b':1}
>>> {v : k for k,v in dict.iteritems()}
{1: 'b'}

HTH,

Raúl

On Mon, Oct 24, 2011 at 3:10 PM, Praveen Singh wrote:

> In Dictionary-
> How to print corresponding keys if the values of dictionary is given??
>
> -d={'a':1,'b':2,'c':3}
> -i can print the corresponding values by using get() method-
> - d.get('a')
> -1
>
> What if i have to print reverse???
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread Dave Angel

On 10/24/2011 09:10 AM, Praveen Singh wrote:

In Dictionary-
How to print corresponding keys if the values of dictionary is given??

-d={'a':1,'b':2,'c':3}
-i can print the corresponding values by using get() method-
- d.get('a')
-1

What if i have to print reverse???


A dictionary can be viewed as a mapping between keys and values, where 
you supply a key, and the dictionary quickly finds the corresponding 
value.  To do the reverse, you have to construct the code yourself and 
it will be much smaller, if there are many items.


For example (untested):

d = {"a", 1, "b":2, "c":3, "d":2}

def getkey(dictionary, value):
 for key, val in dictionary.items():
   if val == value:
  return key


Note that if there are multiple keys with the same value, my function 
would get only the first.  It wouldn't be hard to modify the function to 
return a list of matching keys.


--

DaveA

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


Re: [Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread Dave Angel
(You forgot to include the list on your reply.  Easiest way is to do a 
reply-all when you're replying)


On 10/24/2011 12:21 PM, Praveen Singh wrote:

On Mon, Oct 24, 2011 at 9:18 AM, Dave Angel  wrote:


   

def getkey(dictionary, value):
 for key, val in dictionary.items():
   if val == value:
  return key


Note that if there are multiple keys with the same value, my function would
get only the first.  It wouldn't be hard to modify the function to return a
list of matching keys.





  Thanks DaveA!! i made this programme to return a list of matching
keys...thanks for this outline...
   Can you hint me something in this problem??This is another problem..



invertDictionary({'a':1, 'b':2, 'c':3, 'd':2})

 {1: ['a'], 2: ['b', 'd'], 3: ['c']}

 def reverseLook(dictionary,value):
 a=[]
 d={}
 for key,values in dictionary.iteritems():

 d.update({values:a.append(key)})  // this line is not working//
  print d



No idea what you're trying to do here.  But maybe if you start by 
showing the getkeys() function you wrote for the last assignent, we can 
see if it's useful for doing this one.


Also when you have multiple runtime errors in your program, and don't 
show us the stacktraces, we have to assume you haven't even tried the code.


If I were to run that, I'd get an error calling a non-existent 
invertDictionary().


What do you mean "this line is not working" ?  Is it crashing the 
machine, getting an error (show stacktrace), or just not doing the thing 
you expect?


--

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


Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-24 Thread Alan Gauld

On 24/10/11 11:17, lina wrote:



a quick Q: Every time call the method, need go through the __initi__( ) part?


No.
__init__() is only called when an instance is first created.

Here is an example in the IDLE:

>>> class C:
def __init__(self):
print("I'm in init")
def method(self):
print("I'm in method")


>>> c = C()
I'm in init
>>> c.method()
I'm in method
>>> c2 = C().method()  # calls init for C(), then the method
I'm in init
I'm in method
>>>

HTH,

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

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


[Tutor] string immutability

2011-10-24 Thread Johan Martinez
Hi,

I am struggling to understand Python string immutability. I am able to
modify Python string object after initializing/assigning it a value. So how
does immutability work? I am not following it. Sorry for really stupid
question. Any help?



>>> s = "First"
>>> print s.__class__

>>> print s
First
>>> s = "Second"
>>> print s
Second
>>>



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


Re: [Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread Alan Gauld

On 24/10/11 14:18, Dave Angel wrote:


def getkey(dictionary, value):
   for key, val in dictionary.items():
  if val == value:
 return key


Note that if there are multiple keys with the same value, my function
would get only the first. It wouldn't be hard to modify the function to
return a list of matching keys.


For fun:

def getKeys(aDict, aValue):
return [key for key,val in aDict if val == aValue]

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] string immutability

2011-10-24 Thread Dave Angel

On 10/24/2011 02:04 PM, Johan Martinez wrote:

Hi,

I am struggling to understand Python string immutability. I am able to
modify Python string object after initializing/assigning it a value. So how
does immutability work? I am not following it. Sorry for really stupid
question. Any help?
You're confusing attributes and objects.  When you say  s = "First"  two 
distinct things happen.  An immutable object of type str is created, 
with an immutable value "First".  And then the attribute s is bound to 
that object.  s is not immutable at all.


Then when you do  s = "Second" you are creating a totally different 
immutable object, which s is now bound to. And behind the scenes, the 
first object is garbage collected.


We all confuse this by referring to "variables," but they are not the 
same as "variables" in most other languages.  They never have a value, 
they just refer to an object.  And if you dot = s, you're not 
copying a value at all.  You're just saying that t and s now are bound 
to (refer to) the same object.  If the object is immutable, then you 
don't need the distinction.  But if you mute the object, as opposed to 
creating a new one, both the attributes are still bound to the same object.


Top-level  (global) variables are attributes of the module.  Local 
variables are attributes of the function.  And instance variables (an 
incorrect term) are attributes of an instance, frequently referred to 
asobj.inst


Going from the other end, an object may be bound to one place, two 
places, or many.  And when it's bound to nothing, it gets garbage 
collected (sometimes ref-counted, but that disctinction refers to a 
particular implementation, not to the language Python).  Those "places" 
I'm referring to may be attributes, so we see it as having "a name", but 
it may be bound to something without an explicit name, such as an 
element of a list.


Ints, floats, and strings are immutable.  So I guess the simplest object 
that's mutable is a list.  You can modify the 3rd item in a list without 
affecting any of the "variables" that are bound to it.  But when you use 
any of those variables, it'll appear to have a "new value."


list1 = [3, 0, 44]
list2= list1
list3 = [10, 12, 15, 22]

list1[2] = 45   #mutates the list object bound to list1
  #but list2 is bound to the same object
print list2  #will now be [3, 0, 45]

list2 = list3   #doesn't mutate any objects, it simply rebinds list2 
from the first list object to the second one.


HTH



--

DaveA

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


Re: [Tutor] string immutability

2011-10-24 Thread Sander Sweers
On Mon, 24 Oct 2011, 20:04:20 CEST, Johan Martinez  wrote:

> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So
> how does immutability work? I am not following it. Sorry for really
> stupid question. Any help?

Mutibility means changinging the object (string) in place. What you are doing 
below is creating a new string and asigning it to a variable.
 
> 
> 
> > > > s = "First"
> > > > print s.__class__
> 
> > > > print s
> First
> > > > s = "Second"
> > > > print s
> Second
> > > > 
> 
> 

If the object s reffernces is mutable you should be able to do:

s[0] = 'x'

Try it and see what happen. Then also try this with a list of strings 

s = ['f', 'i', 'r', 's', 't']
s[0] = 'x'

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


Re: [Tutor] string immutability

2011-10-24 Thread Wayne Werner
On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez  wrote:

> Hi,
>
> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So how
> does immutability work? I am not following it. Sorry for really stupid
> question. Any help?
>
> 
>
> >>> s = "First"
> >>> print s.__class__
> 
> >>> print s
> First
> >>> s = "Second"
>

This is not actually modifying the string object. Unlike most other
programming languages where a variable refers to an actual location in
memory (usually), in Python the variable names the actual value.

So when you do s = "First" then you are telling python that you want to be
able to refer to the string "First" by the name/variable s.

When you execute s="Second" you are now telling python that instead of
referring to "First" you want the name 's' to refer to the string "Second".

If you try to modify the actual value of the string, you will raise an
exception:

>>> s = "First"
>>> s[0] = "T"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

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


Re: [Tutor] string immutability

2011-10-24 Thread Steve Willoughby
On Mon, Oct 24, 2011 at 01:04:20PM -0500, Johan Martinez wrote:
> Hi,
> 
> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So how
> does immutability work? I am not following it. Sorry for really stupid
> question. Any help?

No, you're actualy not. 

> >>> s = "First"
> >>> print s
> First

At this point, you have created a string object with the value "First"
and put that into the variable "s" (which is glossing over a detail about 
how Python variables realy work, but that's another topic).

> >>> s = "Second"
> >>> print s
> Second

Now you created a new string object with the value "Second" and stored THAT
into s, replacing the original object, which is now lost.

-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string immutability

2011-10-24 Thread Andreas Perstinger

On 2011-10-24 20:04, Johan Martinez wrote:

Hi,

I am struggling to understand Python string immutability. I am able to
modify Python string object after initializing/assigning it a value.


 s = "First"
 print s.__class__



 print s

First

 s = "Second"
 print s

Second


Dave, Sander and Wayne have already explained why you aren't modifying 
string objects in your example.

With the id()-function you can also see what is happening:

>>> s = "First"
>>> id(s)
3077110080L# In CPython this is the memory address of the object
   # with the name 's' (in your case "First")
>>> s = "Second"
>>> id(s)
3077110304L# You see that 's' refers now to another address
>>> id("First")
3077110080L# But "First" is still on the same address as before
>>> id("Second")
3077110304L# And this proves that "Second" is at the address
   # which 's' refers to

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


Re: [Tutor] string immutability

2011-10-24 Thread Johan Martinez
On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner wrote:

> On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez wrote:
>
>> Hi,
>>
>> I am struggling to understand Python string immutability. I am able to
>> modify Python string object after initializing/assigning it a value. So how
>> does immutability work? I am not following it. Sorry for really stupid
>> question. Any help?
>>
>> 
>>
>> >>> s = "First"
>> >>> print s.__class__
>> 
>> >>> print s
>> First
>> >>> s = "Second"
>>
>
> This is not actually modifying the string object. Unlike most other
> programming languages where a variable refers to an actual location in
> memory (usually), in Python the variable names the actual value.
>
> So when you do s = "First" then you are telling python that you want to be
> able to refer to the string "First" by the name/variable s.
>
> When you execute s="Second" you are now telling python that instead of
> referring to "First" you want the name 's' to refer to the string "Second".
>
> If you try to modify the actual value of the string, you will raise an
> exception:
>
> >>> s = "First"
> >>> s[0] = "T"
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'str' object does not support item assignment
>
> HTH,
> Wayne
>


Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I realized
my wrong understanding/interpretation after posting the message to the list,
which usually  happens most of the time with me!



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


Re: [Tutor] string immutability

2011-10-24 Thread Johan Martinez
On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger <
andreas.perstin...@gmx.net> wrote:

> On 2011-10-24 20:04, Johan Martinez wrote:
>
>> Hi,
>>
>> I am struggling to understand Python string immutability. I am able to
>> modify Python string object after initializing/assigning it a value.
>>
>>   s = "First"
>  print s.__class__
>
 
>>
>>>  print s
>
 First
>>
>>>  s = "Second"
>  print s
>
 Second
>>
>
> Dave, Sander and Wayne have already explained why you aren't modifying
> string objects in your example.
> With the id()-function you can also see what is happening:
>
> >>> s = "First"
> >>> id(s)
> 3077110080L# In CPython this is the memory address of the object
>   # with the name 's' (in your case "First")
> >>> s = "Second"
> >>> id(s)
> 3077110304L# You see that 's' refers now to another address
> >>> id("First")
> 3077110080L# But "First" is still on the same address as before
> >>> id("Second")
> 3077110304L# And this proves that "Second" is at the address
>   # which 's' refers to
>
> Bye, Andreas
>

Great, that's really helpful Andreas.

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


Re: [Tutor] string immutability

2011-10-24 Thread Dipo Elegbede
What you did here is just re-assigning s.
Try slicing s and then assign a new value to the slice.
s[2] would return 'r' now try to to set s[2] to another value to understand
immutability.
Hope it helps.

On 24 Oct 2011 19:06, "Johan Martinez"  wrote:

> Hi,
>
> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So how
> does immutability work? I am not following it. Sorry for really stupid
> question. Any help?
>
> 
>
> >>> s = "First"
> >>> print s.__class__
> 
> >>> print s
> First
> >>> s = "Second"
> >>> print s
> Second
> >>>
>
> 
>
> jM.
>
> ___
> 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] string immutability

2011-10-24 Thread Steve Willoughby

On 24-Oct-11 12:17, Johan Martinez wrote:

Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I
realized my wrong understanding/interpretation after posting the message
to the list, which usually  happens most of the time with me!


That happens to most of us all the time too :)  Unfortunately, with the 
lag between posting to the list and mail getting out to everyone, you'll 
probably get several replies that all say the same thing--we're not 
piling up on you, it's just a bunch of people being helpful without 
seeing that someone already answered yet.


Glad we could help.  Looking more into how Python variables work unlocks 
a lot of potential for all sorts of data structure operations that other 
languages require pointers to do, but are a lot easier when essentially 
all "variables" are references to objects but with the details handled 
behind the scenes for you.


--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string immutability

2011-10-24 Thread Dave Angel

On 10/24/2011 03:21 PM, Johan Martinez wrote:

On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger<
andreas.perstin...@gmx.net>  wrote:


On 2011-10-24 20:04, Johan Martinez wrote:


Hi,

I am struggling to understand Python string immutability. I am able to
modify Python string object after initializing/assigning it a value.

   s = "First"

  print s.__class__




  print s

First

  s = "Second"

  print s


Second

Dave, Sander and Wayne have already explained why you aren't modifying
string objects in your example.
With the id()-function you can also see what is happening:


s = "First"
id(s)

3077110080L# In CPython this is the memory address of the object
   # with the name 's' (in your case "First")

s = "Second"
id(s)

3077110304L# You see that 's' refers now to another address

id("First")

3077110080L# But "First" is still on the same address as before

id("Second")

3077110304L# And this proves that "Second" is at the address
   # which 's' refers to

Bye, Andreas


Great, that's really helpful Andreas.

thanks,
jM.

Unfortunately, that trick is not guaranteed to work.  The only reason 
that id("First") gives the same value as  s="First"; id(s) is that 
"First" is one of the few magic values that get cached.  Small 
non-negative integers and short strings without spaces tend to be in 
that category, but you can't count on it.


Try
a = 400
b = 400
print id(a), id(b)
  it'll probably print different numbers, if the value 400 isn't one of 
the "cached" values.



Worse is that an id() can be reused once an object is garbage 
collected.  So I could do something like:

a = 600
print id(a)
del a
b = 400
print id(b)
and it might print the same value.  There are more subtle cases, 
but I wanted to keep it simple.
An id() is guaranteed to be unique across all objects that exist at the 
same moment.  So as long as you're comparing id's of two objects that 
are both present, you're fine.


I'm afraid to really understand id(), you have to understand how the 
object model works, so you can't use id() to prove it.


--

DaveA

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


Re: [Tutor] string immutability

2011-10-24 Thread Johan Martinez
On Mon, Oct 24, 2011 at 2:32 PM, Steve Willoughby  wrote:

> On 24-Oct-11 12:17, Johan Martinez wrote:
>
>> Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I
>> realized my wrong understanding/interpretation after posting the message
>> to the list, which usually  happens most of the time with me!
>>
>
> That happens to most of us all the time too :)  Unfortunately, with the lag
> between posting to the list and mail getting out to everyone, you'll
> probably get several replies that all say the same thing--we're not piling
> up on you, it's just a bunch of people being helpful without seeing that
> someone already answered yet.
>
> Glad we could help.  Looking more into how Python variables work unlocks a
> lot of potential for all sorts of data structure operations that other
> languages require pointers to do, but are a lot easier when essentially all
> "variables" are references to objects but with the details handled behind
> the scenes for you.
>
> --
> Steve Willoughby / st...@alchemy.com
> "A ship in harbor is safe, but that is not what ships are built for."
> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


Actually it's good to see so many replies and different methods and
explanations here.

Also, is there any doc link where I can find all the information about
String object - class and instance methods. Google pointed me to following
two links, but that wasn't helpful for finding instance method for finding
length of a string object (rather than using 'len' function).

- http://docs.python.org/library/string.html
- http://docs.python.org/library/stdtypes.html#string-methods

Finally I figured it out ( __length__() ) thanks to ipython shell env. But
is there any online documentation or interactive reference like ruby-ri?

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


Re: [Tutor] string immutability

2011-10-24 Thread Joel Goldstick
the len() function works on lots of objects:

>>> a = "this is a string"
>>> len(a)
16


On Mon, Oct 24, 2011 at 3:52 PM, Johan Martinez  wrote:

>
>
> On Mon, Oct 24, 2011 at 2:32 PM, Steve Willoughby wrote:
>
>> On 24-Oct-11 12:17, Johan Martinez wrote:
>>
>>> Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I
>>> realized my wrong understanding/interpretation after posting the message
>>> to the list, which usually  happens most of the time with me!
>>>
>>
>> That happens to most of us all the time too :)  Unfortunately, with the
>> lag between posting to the list and mail getting out to everyone, you'll
>> probably get several replies that all say the same thing--we're not piling
>> up on you, it's just a bunch of people being helpful without seeing that
>> someone already answered yet.
>>
>> Glad we could help.  Looking more into how Python variables work unlocks a
>> lot of potential for all sorts of data structure operations that other
>> languages require pointers to do, but are a lot easier when essentially all
>> "variables" are references to objects but with the details handled behind
>> the scenes for you.
>>
>> --
>> Steve Willoughby / st...@alchemy.com
>> "A ship in harbor is safe, but that is not what ships are built for."
>> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
>
>
> Actually it's good to see so many replies and different methods and
> explanations here.
>
> Also, is there any doc link where I can find all the information about
> String object - class and instance methods. Google pointed me to following
> two links, but that wasn't helpful for finding instance method for finding
> length of a string object (rather than using 'len' function).
>
> - http://docs.python.org/library/string.html
> - http://docs.python.org/library/stdtypes.html#string-methods
>
> Finally I figured it out ( __length__() ) thanks to ipython shell env. But
> is there any online documentation or interactive reference like ruby-ri?
>
> jM.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] reg current work in pycrypto

2011-10-24 Thread Steven D'Aprano

nivedita datta wrote:

Hi all,

Can anyone tell me about some projects or applications which has been built
using pycrypto. Also I would like to know about any ongoing/past project or
application development in pycrypto.


This is a mailing list for beginners learning the basics of Python 
programming, not for arbitrary questions about third-party advanced 
cryptography libraries.


You might be lucky to find someone here who happens to have used 
pycrypto, but I would be surprised if it happens. You would be better 
off asking on any pycrypto mailing lists or other forums. If all else 
fails, try the main Python discussion list, comp.lang.python.



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


Re: [Tutor] regex and parsing through a semi-csv file

2011-10-24 Thread Mina Nozar

Hi Marc,

Thank you.  Following some of your suggestion, the rewrite below worked.  I agree with your point on readability over 
complexity.  By grace I meant not convoluted or simpler.  That's all.  As a beginner, I find not knowing all the 
existing functions, I end up re-inventing the wheel sometimes.



Cheers,
Mina


isotope_name,isotope_A = args.isotope.split('-')
print isotope_name, isotope_A

found_isotope = False
activity_time = []
activity = []
activity_err = []


f = open(args.fname, 'r')
lines = f.readlines()
f.close()

for i, line in enumerate(lines):
line = line.strip()
if isotope_name in line and isotope_A in line:
found_isotope = True
print 'found isotope'
#print line
lines = lines[i+1:]
break

for line in lines:
line = line.strip()
if not line[0].isdigit():
break
print 'found'
words = line.split(',')
activity_time.append(float(words[0]))
activity.append(float(words[1]))
activity_err.append(float(words[2]))

On 11-10-19 12:06 PM, Marc Tompkins wrote:

On Wed, Oct 5, 2011 at 11:12 AM, Mina Nozar mailto:noz...@triumf.ca>> wrote:

Now, I would like to parse through this code and fill out 3 lists: 1) 
activity_time, 2) activity, 3) error, and plot
the activities as a function of time using matplotlip.  My question 
specifically is on how to parse through the
lines containing the data (activity time, activity, error) for a given 
isotope, stopping before reaching the next
isotope's info.


Regular expressions certainly are terse, but (IMHO) they're really, really hard 
to debug and maintain; I find I have to
get myself into a Zen state to even unpack them, and that just doesn't feel 
very Pythonic.

Here's an approach I've used in similar situations (a file with arbitrary 
sequences of differently-formatted lines,
where one line determines the "type" of the lines that follow):
-  create a couple of status variables: currentElement, currentIsotope
-  read each line and split it into a list, separating on the commas
-  look at the first item on the line: is it an element?  (You could use a list 
of the 120 symbols, or you could just
check to see if it's alphabetic...)
   -  if the first item is an element, then set currentElement and 
currentIsotope, move on to next line.
-  if the first item is NOT an element, then this is a data line.
   -  if currentElement and currentIsotope match what the user asked for,
  -  add time, activity, and error to the appropriate lists
   - if not, move on.

This approach also works in the event that the data wasn't all collected in 
order - i.e. there might be data for Ag111
followed by U235 followed by Ag111 again.

Note that the size of the lists will change depending on the number of 
activities for a given run of the simulation
so I don't want to hard code '13' as the number of lines to read in 
followed by the line containing isotope_name, etc.


This should work for any number of lines or size of file, as long as the data 
lines are all formatted as you expect.
Obviously a bit of error-trapping would be a good thing

If there is a more graceful way of doing this, please let me know as well.  
I am new to python...

For me, readability and maintainability trump "grace" every time.  Nobody's 
handing out awards for elegance (outside of
the classroom), but complexity gets punished (with bugs and wasted time.)  More 
elegant solutions might also run faster,
but remember that premature optimization is a Bad Thing.



___
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] Simple Question On A Method (in subclass)

2011-10-24 Thread bob gailer

On 10/24/2011 7:45 AM, Wayne Werner wrote:
On Sun, Oct 23, 2011 at 11:06 PM, Marc Tompkins 
mailto:marc.tompk...@gmail.com>> wrote:


Things to remember:
-you can get a value from a method, but you can't assign to it:
variable = object.method()
but NOT
object.method() = variable


As a slight aside, you _can_ assign to the method name:

object.method = variable #object.method is now whatever variable was

I'm not aware of any valid reason to do this, that is to say I don't 
know of anything that you could do this way that you couldn't do 
another more readable/maintainable way.


In my Python Pipelines program I deliberately reassign instance methods. 
Example:


Given a (trivial) pipeline specification: "< foo.txt | > goo.txt"
meaning: "open foo.txt, open goo.txt, read one record at a time from 
foo.txt, write it to goo.txt, at end close both files."
The specification parser creates an instance of ReadFile and an instance 
of WriteFile, It must then "connect" these two instances, such that the 
output of the first goes to the input of the second. The IMHO easiest 
way to do this: instance1.output = instance2.input where output and 
input are methods.


I've had other cases where the __init__method of a class determines some 
behaviors by assigning one of several methods to a particular method.


I've had yet other cases where I swap methods during the first call, 
such that subsequent calls have different behavior.


All of these could be done differently, but reassigning methods makes 
the most sense to me.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread bob gailer
Another approach is to subclass dict such that each time you add a 
key:value pair you also create an entry in a reverse dictionary. Then 
all you need do is lookup in the reverse dictionary.


If there are several keys with the same value, then create and extend a 
list of values in the reverse dictionary.


This will fail (as any other reverse dictionary approach will)  if the 
values are not hashable


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


[Tutor] Quacks like an object

2011-10-24 Thread Christopher King
Dear Tutors,
I am trying to make an object, which will appear exactly like an object
of my choice. It will should be impossible to tell it is not the object.
This is because I am making an object that modifies it methods so that if
the methods make a change to the object, it will sync those changes to a
file, but I don't want it to be another object, so foreign functions will
not mistake for not being the object. For example
if, I used type on the object, it should return the class of the object it
is trying to mimic. I have tried everything from modifying the object's get
set attribute methods, to having making a new object that has get and set
the same as the object except with a filter for methods, but I had no luck.
In a nutshell, I want an object that walks like another object, quacks like
another object, and basically is another object. Is this possible?

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


Re: [Tutor] How to print corresponding keys in Dictionary

2011-10-24 Thread Alan Gauld

On 24/10/11 19:00, Alan Gauld wrote:

For fun:

def getKeys(aDict, aValue):
return [key for key,val in aDict if val == aValue]


Oops, that should have been

 return [key for key,val in aDict.items() if val == aValue]


--
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] string immutability

2011-10-24 Thread Alan Gauld

On 24/10/11 20:52, Johan Martinez wrote:


Also, is there any doc link where I can find all the information about
String object - class and instance methods.



>>> help(str)

or even

>>> help("")

For a quick list try dir()

>>> dir ("")



Finally I figured it out ( __length__() ) thanks to ipython shell env.


len(x)

gets converted to x.__length__() by Python.
So you can make any object work with len() by providing
a __length__() method. Similarly you can make any object into a string 
by providing a __str__() metjod and then str(obj) will work (as will 
print (obj) )


There are a bunch of these "magic" methods that you can provide to help 
make your objects appear more like the standard built in objects.



But is there any online documentation or interactive reference like
ruby-ri?


There are various help browsers for Python.
The one that comes with ActiveState Python for Windows is quite good 
IMHO and integrates with Windows Help too.


But personally I just use dir() and help() and Google...



--
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] Quacks like an object

2011-10-24 Thread Alan Gauld

On 25/10/11 00:02, Christopher King wrote:

Dear Tutors,
 I am trying to make an object, which will appear exactly like an
object of my choice. It will should be impossible to tell it is not the
object.


We can get pretty close but I suspect its impossible to make it 100% 
reliable - otherwise Python itself would get confused!


>  This is because I am making an object that modifies it methods

so that if the methods make a change to the object, it will sync those
changes to a file, but I don't want it to be another object,
so foreign functions will not mistake for not being the object.


Sorry that bit lost me!
You want to persist data changes to a file? Thats easy enough.
But the last two lines sem disconnected fro the saving to file bit?

> For example if, I used type on the object, it should return
> the class of the object it is trying to mimic.

And presumably isinstance() too?


but I had no luck. In a nutshell, I want an object that walks like
another object, quacks like another object, and basically is another
object.


But basically is NOT another object I think you mean.
If you really want it to be the other object then just make another 
instance cloning the attributes. But I don;t think thats really what you 
want?



Is this possible?


If you are prepared to spend a lot of time implementing all the meta 
methods etc then you should be able to get pretty close. But it
will be tedious. I suspect there will almost certainly be a better 
solution if we understood the actual problem you are trying to solve. 
(The facade design pattern sounds likely for 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] Simple Question On A Method (in subclass)

2011-10-24 Thread Chris Kavanagh



On 10/24/2011 12:06 AM, Marc Tompkins wrote:

On Sun, Oct 23, 2011 at 8:08 PM, Chris Kavanagh mailto:cka...@msn.com>> wrote:

So we have {member.tell} as the last line of code. So trying to
understand this piece of code, {member} the variable is considered
an object? Therefore we can combine it with a function {tell()}
using dot notation?? Is this correct??? I haven't seen anything but
an object combined with a function using dot notation. When I say
"object", I mean an "object" created from a class. So I'm trying to
figure out how we can combine the variable {member} with the
function {tell}. Hope this question makes sense to you, LOL. Thanks
again.


First of all: other languages distinguish between variables and objects,
and between functions and objects, but in Python both variables and
functions are objects.  EVERYTHING is an object.  This is an important
thing to remember - even if you never create classes of your own (which
would be a terrible waste, BTW) a lot of the language won't make sense
unless you remember that everything's an object.

Second, the line "members = [t, s]" creates a list "members" (which is
also an object, by the way!) containing two objects - "t" is a Teacher,
"s" is a Student - which are both subclassed from SchoolMember.
The line "for member in members" means: step through the list "members"
and work with each object we find in it; let's call that object "member"
while we're working with it.  As soon as we finish with the first object
and move on to the next, call the next one "member" - and so on.  The
beauty of this approach is that it simply doesn't matter what the
contents of the list are - one could be a Student, the next a
WoollyMammoth - and as long as your code only references methods and
attributes that work for all the items in the list, Python won't care.

Third, dot notation:  objects have "methods" (which in non-OOP contexts
would be called "functions") and "attributes" (variables, more or
less.)  From outside of the class definition, you refer to the object's
attributes like so:
 variable = object.attribute # if you want to read the attribute's
current value
or
 object.attribute = variable # if you want to set the attribute to a
new value

and to its methods like so:
 variable = object.method(parameter1, parameter2, etc)

Like all functions, methods can take a fixed number of parameters, an
optional bunch of named parameters, or no parameters at all; they may
return a value or they may not; you may want to use that value, or
ignore it.

Things to remember:
-you can get a value from a method, but you can't assign to it:
 variable = object.method()
but NOT
 object.method() = variable

-the only visible difference between reading an attribute and calling a
method with no parameters is the parentheses at the end.  Don't forget
them, and don't be misled by the similarity.

Hope that helps...



Thanks so much for the explanation Marc!

My problem was, I wasn't seeing {member} as referring to the class 
objects {t} and {s}. Since it was, we now can use member just like any 
class object, and combine it with class functions (and class variables), 
such as {member.tell}. I had never in my short programming experience, 
seen an example like this. So I was confused, obviously, LOL.


Makes perfect sense now. . .Thanks again Marc (and Alan, Dave)
BTW, do you guys luv Python the way I do!?? I just luv the way 
everything works together so explicitly. I LUV learning this stuff!!

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


Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-24 Thread Marc Tompkins
On Mon, Oct 24, 2011 at 9:20 PM, Chris Kavanagh  wrote:

> Makes perfect sense now. . .Thanks again Marc (and Alan, Dave)
> BTW, do you guys luv Python the way I do!?? I just luv the way everything
> works together so explicitly. I LUV learning this stuff!!
>

Oh yeah, baby.  Python makes programming fun again.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Question On A Method (in subclass)

2011-10-24 Thread Marc Tompkins
On Mon, Oct 24, 2011 at 3:44 PM, bob gailer  wrote:

>  On 10/24/2011 7:45 AM, Wayne Werner wrote:
>
> On Sun, Oct 23, 2011 at 11:06 PM, Marc Tompkins 
> wrote:
>
>>  Things to remember:
>>  -you can get a value from a method, but you can't assign to it:
>> variable = object.method()
>> but NOT
>> object.method() = variable
>>
>
>  As a slight aside, you _can_ assign to the method name:
>
>  object.method = variable #object.method is now whatever variable was
>
>  I'm not aware of any valid reason to do this, that is to say I don't know
> of anything that you could do this way that you couldn't do another more
> readable/maintainable way.
>
>
> In my Python Pipelines program I deliberately reassign instance methods.
> Example:
>
> Given a (trivial) pipeline specification: "< foo.txt | > goo.txt"
> meaning: "open foo.txt, open goo.txt, read one record at a time from
> foo.txt, write it to goo.txt, at end close both files."
> The specification parser creates an instance of ReadFile and an instance of
> WriteFile, It must then "connect" these two instances, such that the output
> of the first goes to the input of the second. The IMHO easiest way to do
> this: instance1.output = instance2.input where output and input are methods.
>
> I've had other cases where the __init__method of a class determines some
> behaviors by assigning one of several methods to a particular method.
>
> I've had yet other cases where I swap methods during the first call, such
> that subsequent calls have different behavior.
>
> All of these could be done differently, but reassigning methods makes the
> most sense to me.
>

As Einstein said, "Everything should be made as simple as possible, but not
simpler."  I also reassign methods (it's not my first choice, but sometimes
it's the best way to do what I want to do) but I thought it would muddy the
waters if I brought it up.  I apologize for over-simplifying.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor