Tomaz Bevec | 1 Aug 02:09 2008
Picon

Re: Mixing in and Mixing out classes in python

Thanks for your reply Alan,

I am partially asking out of interest, but I also have a potential application.

I'm working on a simulation of cellular growth patterns (basically cell instances interacting
stochastically on a lattice).  Anyway, there are many different cell "behaviors" that I have to simulate,
and cells can potentially gain and lose these "behaviors" over the course of the simulation.  It would be
too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing
it in (and initializing it) when necessary or when biological function is gained by the cells.

In addition some of the behaviors would be too big (as in lines of code) if they were implemented in one
function so splitting functionality up in my mixin class makes it conceptually easier for me.  Also the
behaviors sometimes need access to the internals of the cell class.  After I mixin a class every method that
starts with the word 'behavior.*' in that class is called when I update the simulation.  All of my mixins
inherit from "object" only.

So far my approach is working well, but I don't have a clean way for cells to lose functionality.  Hence my
question about mixin out.  I tried to just delete the 'behavior.*' functions with the del operator (like
for an attribute) but it didn't work.

I have however thought of a number of ways to work around this, and per your suggestion I think I'll just try
something else, but if you have any idea on how to dynamically mix out I'd be glad to here it.

Thanks,
Tomaz

--- On Thu, 7/31/08, Alan Gauld <alan.gauld <at> btinternet.com> wrote:

> From: Alan Gauld <alan.gauld <at> btinternet.com>
> Subject: Re: [Tutor] Mixing in and Mixing out classes in python
(Continue reading)

Kent Johnson | 1 Aug 02:29 2008
Picon

Re: Mixing in and Mixing out classes in python

On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec <tomazbevec <at> yahoo.com> wrote:
> Thanks for your reply Alan,
>
> I am partially asking out of interest, but I also have a potential application.
>
> I'm working on a simulation of cellular growth patterns (basically cell instances interacting
stochastically on a lattice).  Anyway, there are many different cell "behaviors" that I have to simulate,
and cells can potentially gain and lose these "behaviors" over the course of the simulation.  It would be
too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing
it in (and initializing it) when necessary or when biological function is gained by the cells.

Perhaps you could keep the behaviors in a dictionary? You could
override __getattr__() in the cell class to look up attributes whose
names start with 'behavior' in the dict.

Kent
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Chris Fuller | 1 Aug 04:57 2008
Picon

Re: key/value order in dictionaries

On Thursday 31 July 2008 05:33, Monika Jisswel wrote:
> Python dictionaries are not ordered & the order you will get when you print
> a dictionary is the order that the python virtual machines thinks optimal
> for that dictionary for its own internal procedures.

If you need an ordered dictionary, such things exist.  The implementation I 
use is at http://www.voidspace.org.uk/python/modules.shtml, but there may be  
one or two other popular ones out there.  You probably shouldn't use them 
unless you have a specific need to.  They will be a lot slower, and extra 
dependencies always complicates distribution.

Cheers
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Angela Yang | 1 Aug 05:16 2008
Picon

how do I create a lists of values associated with a key?

Hi,

I have a list of values for one key.  How do I specify this data structure?

First tried,

collection = []
collection['abby'].append('apprentice1')
collection['abby'].append('apprentice2')

That did not work because list index is not numeric.
But for dictionaries, it is key - value pairs.  But I need key -> multiple values.

Do you have some example how to specify this?

Angela



_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor
Federo | 1 Aug 09:39 2008
Picon

Is anybody out there who could help me with URL Authentication?

Hi ..

I have to admit that Python is really surprising me. It was lucky day a few 
weeks ago I firts time start using Python. Lot's of things realy can be done 
with short learning curve. Your user guieds was best place to start!

Below is problem I am unable to solve. I would appreciate your advice or 
even better code sample. The problem is URL authorisation. I try to approaches 
but no luck so far. Two problems:

1.) Being able to logon using Python code
2.) Being able to send data to a form and get back server reply

ad 1.)
The Two pages I try to open:

Login:
https://investor.firstrade.com/firstrade/login.do
Main page after login:
https://investor.firstrade.com/firstrade/mainmenu.do

I have tried bellow code (with currect user name and password of course):
>>> import urllib2
>>> password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
>>> protocol = 'https://'
>>> username = 'user'
>>> password = 'pass'
>>> top_level_url = "investor.firstrade.com/firstrade/login.do"
>>> password_mgr.add_password(None, top_level_url, username, password)
>>> handler = urllib2.HTTPBasicAuthHandler(password_mgr)
>>> opener = urllib2.build_opener(handler)
>>> a_url = "https://investor.firstrade.com/firstrade/login.do"
>>> f = opener.open(a_url)
>>> a = f.read()
>>> print (a)

but it replied login page after login. It looks like they are using cookie. 
Bellow line can be find in header
Set-Cookie: JSESSIONID=351CE048D9FEAD01E21604129D38725C; Path=/; Secure

On the web I found user guide explaining coookie login. However I do not 
understand how to combine now password and cookie login if this will solve the 
problem at first place... 
http://www.voidspace.org.uk/python/articles/cookielib.shtml#fetching-webpages

CODE SAMPLE to be able to solve the problem very appreciated..

There is by pass solution using Web Recorder Macro. However it will be much 
better to BE ABLE TO handle entire process with Python..

ad 2.) Filling data to form / getting beck server values. I need server reply 
from the same web side we are discussing in point 1.

Here is Code sample:
import urllib
import urllib2  

    url = 'https://investor.firstrade.com/firstrade/mainmenu.do'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'    
    values = {'symbol' : 'xsnx'}

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()

a.) I do not understand where can I find currect fields names for values 
in the above code sample (in our case "Symbol" is written before Text box (look 
attached print screen. HTML code of main side is attached file 
Firstrade_MainSideHTML.rtf) 
where you can write stock ticker and than press a button. Server replied real 
time stock data which I would like to read)?
b.) Probably code will be more complex as sample code above as code has to take 
care also for proper authorisation..

Sorry for taking your time. Your help would be very useful as I stacked with 
this. Being able to handle URL requests is very important now days...

Cheers, Fedo

____________________
http://www.email.si/

____________________
http://www.email.si/
Attachment (Firstrade_MainSideHTML.rtf): application/msword, 54 KiB
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor
Marc Tompkins | 1 Aug 12:20 2008
Picon

Re: how do I create a lists of values associated with a key?



On Thu, Jul 31, 2008 at 8:16 PM, Angela Yang <angelayian <at> yahoo.com> wrote:
Hi,

I have a list of values for one key.  How do I specify this data structure?

First tried,

collection = []
collection['abby'].append('apprentice1')
collection['abby'].append('apprentice2')

That did not work because list index is not numeric.
But for dictionaries, it is key - value pairs.  But I need key -> multiple values.

Do you have some example how to specify this?

Angela

Each "value" can, itself, be a container - a tuple, a list, or another dictionary.

dictTuple = {"a":(1,2,3), "b":(4,5,6)}
dictList = {"a":[1,2,3], "b":[4,5,6]}
dictDict = {"a":{"c":"1","d":"2","e":"3"}, "b":{"f":"4","g":"5","h":"6"}}

Retrieving values:
valValue = dictTuple["a"][0]  # 1
valValue = dictTuple["b"][2]  # 6

Lists work just the same:
valValue = dictList["a"][0]  # 1
valValue = dictList["b"][2]  # 6

Dictionaries are, well, like dictionaries:
valValue = dictDict["a"]["c"]  # 1
valValue = dictDict["b"]["h"]  # 6


Hope that helps....

--
www.fsrtechnologies.com
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor
Alan Gauld | 1 Aug 12:21 2008

Re: Mixing in and Mixing out classes in python

"Tomaz Bevec" <tomazbevec <at> yahoo.com> wrote

> I'm working on a simulation of cellular growth patterns ...and cells
> can potentially gain and lose these "behaviors" over the course
> of the simulation.

OK, That might be a valid scenario.
But personally I'd probably implement that as an
attribute of the cell - a list of behaviours and build
a Behaviour class with subclasses. The methods
of which take a Cell class as their argument.

It is then trivial to add remove behaviours.
And simply call them in a loop

for b in self.behavious:
    b.doit(self)

Or maybe have a dictionary of behaviours
if you even want to call specific ones.

eg

def myMeth(self):
      # do sometjing
      try: self.behaviours['behaviourMyMeth'](self)
      except KeyError: pass
      # do the rest

> I have however thought of a number of ways to work around this,
> and per your suggestion I think I'll just try something else,

I'd come back to the old OOP adage, inheritance is for Is-A 
relationships.
Is you Cell a behaviour or does it Have-A behaviour?

With mixins that adage tends to get bent since mixins are often
functional in nature but if the function is not intrinsic to the class
I tend to use delegation.

> any idea on how to dynamically mix out I'd be glad to here it.

I don't know but I'm sure its possible if you understand the class
internals well enough.

Regards,

Alan G. 

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Alan Gauld | 1 Aug 12:25 2008

Re: how do I create a lists of values associated with a key?


"Angela Yang" <angelayian <at> yahoo.com> wrote

> But for dictionaries, it is key - value pairs. But I need key -> 
> multiple values.

But a value can be a list.

d = {}
d['odd'] = [1,3,5,7]
d['even'] = [2,4,6,8]

print d['odd'][2]    # = 5

See the Raw Materials top[ic in my tutorial for another
example using a dictionary to store address data:

>>> addressBook = {
... 'Fred' : ['Fred', '9 Some St',' Anytown', '0123456789'],
... 'Rose' : ['Rose', '11 Nother St', 'SomePlace', '0987654321']
... }>>> print addressBook['Rose']
['Rose', '11 Nother St', 'SomePlace', '0987654321']
>>> print addressBook['Fred'][3]
0123456789
HTH,

--

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Tomaz Bevec | 1 Aug 12:25 2008
Picon

Re: __getattribute__ instead of Mixing in and Mixing out classes in python


Thanks for your suggestion, Kent.  I've looked into it a little bit and I think its probably the right way to
go.  

--- On Thu, 7/31/08, Kent Johnson <kent37 <at> tds.net> wrote:

> From: Kent Johnson <kent37 <at> tds.net>
> Subject: Re: [Tutor] Mixing in and Mixing out classes in python
> To: tomazbevec <at> yahoo.com
> Cc: "Tutor Python" <tutor <at> python.org>
> Date: Thursday, July 31, 2008, 5:29 PM
> On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec
> <tomazbevec <at> yahoo.com> wrote:
> > Thanks for your reply Alan,
> >
> > I am partially asking out of interest, but I also have
> a potential application.
> >
> > I'm working on a simulation of cellular growth
> patterns (basically cell instances interacting
> stochastically on a lattice).  Anyway, there are many
> different cell "behaviors" that I have to
> simulate, and cells can potentially gain and lose these
> "behaviors" over the course of the simulation.  It
> would be too much to put every behavior function in the cell
> class, so I'm writing each behavior as a mixin and
> mixing it in (and initializing it) when necessary or when
> biological function is gained by the cells.
> 
> Perhaps you could keep the behaviors in a dictionary? You
> could
> override __getattr__() in the cell class to look up
> attributes whose
> names start with 'behavior' in the dict.
> 
> Kent

      
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Benoit Thiell | 1 Aug 12:29 2008
Picon
Picon

Re: how do I create a lists of values associated with a key?

Dear Angela,

in order to do this, the setdefault function of the dictionaries is very 
useful.

For example:
mydict = {}
mylist = mydict.setdefault(mykey, [])
mylist.append(myvalue)

"setdefault" either returns the already existing list or sets a new list 
for the key and returns it.

Regards,
Benoit Thiell.

On Fri, 1 Aug 2008, Marc Tompkins wrote:

> 
> 
> On Thu, Jul 31, 2008 at 8:16 PM, Angela Yang <angelayian <at> yahoo.com> wrote:
>       Hi,
>
>       I have a list of values for one key.  How do I specify this data structure?
>
>       First tried,
>
>       collection = []
>       collection['abby'].append('apprentice1')
>       collection['abby'].append('apprentice2')
>
>       That did not work because list index is not numeric.
>       But for dictionaries, it is key - value pairs.  But I need key -> multiple values.
>
>       Do you have some example how to specify this?
>
>       Angela
> 
> 
> Each "value" can, itself, be a container - a tuple, a list, or another dictionary.
> 
> dictTuple = {"a":(1,2,3), "b":(4,5,6)}
> dictList = {"a":[1,2,3], "b":[4,5,6]}
> dictDict = {"a":{"c":"1","d":"2","e":"3"}, "b":{"f":"4","g":"5","h":"6"}}
> 
> Retrieving values:
> valValue = dictTuple["a"][0]  # 1
> valValue = dictTuple["b"][2]  # 6
> 
> Lists work just the same:
> valValue = dictList["a"][0]  # 1
> valValue = dictList["b"][2]  # 6
> 
> Dictionaries are, well, like dictionaries:
> valValue = dictDict["a"]["c"]  # 1
> valValue = dictDict["b"]["h"]  # 6
> 
> 
> Hope that helps....
> 
> --
> www.fsrtechnologies.com
> 
>
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Gmane