[Tutor] calling class instances in functions

Michael Langford mlangford.cs03 at gtalumni.org
Wed Sep 12 15:38:18 CEST 2007


I too am a little confused what exactly you're going for, but here is a shot
at the two things I think you could be asking for:

If you're trying to create a world where you have it populated with several
different types of cells at different coordinates, and you'd like to make it
so the user can select one of the already created cells, I suggest making a
class for the world, and having its str method create a text list something
like so you can use it for printing out to the user if they need to interact
with the individual cells.

1. Yeast(0,4)
2. Malaria(5,6)
3. Gondrii(5,8)
4. Yeast(5,9)
...

Etc.

World would use getattr to get the name of the class of each cell on it, and
would append the position. I'd make a function that will be able to get
cells based on the number that the user selected. Also, a dictionary keyed
off a positions tuple will probably work just fine for your world and will
also be a lot easier and faster to access and enumerate, especially if you
make the field very very large.

ie, You could populate the world like this non interactively:

world_data = {}
word_data[(0,4)] = Yeast()
word_data[(5,6)] = Malaria()
word_data[(5,8)] = Gondrii()
word_data[(5,9)] = Yeast()

================

Now if I've misunderstood, and you're talking about making NEW cells of
various types and the user dynamically tells you what places to put what
cells, here is how you do that.

In your main, I would collect a list of all the types of microbes you can
create and cycle through them to get their names, and use the users choices
to make them and use the users choice of position to insert them in the
world:

myWorld = World()
theMicrobes = [Yeast,Malaria,Gondrii]

print "Please type the name of the microbe you wish to create:"
for each in theMicrobes:
       cls = getattr(each,"__class__")
       print cls.__name__

microbeToCreateRaw= raw_input()
#
#do some stuff here to cleanup the input
#

for each in theMicrobes:
    cls = getattr(each,"__class__")
    if microbeToCreate == cls.__name__:
           newMicrobe = cls()

#Now you find where they wish to drop it in the world
print "Where do you want it in the world?"

rawCoords = raw_input()

#parse out the x and y
#
# Left to the reader to parse out
#

myWorld.insertAt(newMicrobe,x,y) #assuming you made a class for the world

         --Michael


On 9/11/07, Ara Kooser <ghashsnaga at gmail.com> wrote:
>
> Thank you for your help on classes. I am working on an old program I
> started in 2005. This time around I am trying to model cell behavior
> using a PD model. I have the main program and then a file called
> yeast_cell.py that contains the classes I want to instance.
>
> In the main program at the function def add_yeast(world): I want to
> instance the class GoodYeast and have the global variable @ change to
> G on the world. I tried just creating an instance but that did not go
> over so well. I was wondering what is the proper and pythonic way to
> create an instance that the user will be selecting in a function. I
> eventually want to add a bunch of different cell classes.
>
> Thank you for your help.
>
> Ara Kooser
>
>
> Main Program
> ########################################################################
> #Yeast Cooperation Model
> #by Ara Kooser
> #Version 1.0 no PD, 070906
> #
> #This code contain just the world setup and not the actually PD code
> #for copperation behavior. This is better left to classes not functions
> #
> #TO DO LIST: Add error handling, dump to text file, data gathering,
> #different classes of yeast
> #
> #Many thanks to: Danny Yoo, Lee Haar, Max Noel, Kent Johnson
> ########################################################################
>
> import random
> import copy
> import textwrap
> import yeast_cell
>
>
> #########################################################################
> #This section of the code sets up and prints out the starting conditions
> #of the world and the yeast
> ########################################################################
>
>
> YEAST, EMPTY, GROUP = '@', '.', 'Q'
>
>
> def percolation(perc):
> #Sets up a percolation threshold value
>     randval = random.random()
>     if randval > perc:
>         return EMPTY
>     else:
>         return YEAST
>
> def random_world(M, N):
> #Constructs random world of size MxN
>     world = {}
>     for j in range(N):
>         for i in range(M):
>             world[i, j] = percolation(perc)
>     world['dimensions'] = (M, N)
>     return world
>
> def print_world(world):
> #Prints out a string representation of a world.
>     M, N = world['dimensions']
>     for j in range(N):
>         for i in range(M):
>             print world[i, j],
>         print
>
>
> def add_yeast(world):
> #Allows the user to add a yeast cell at point m,n
>     M,N = world['dimensions']
>     new_world = copy.copy(world)
>
>     counta = 0
>
>     yy = raw_input("How many yeast cells do you wish to add?")
>     yy = int(yy)
>
>     while counta<yy:
>         zz = raw_iput("What kind of yeast cell do you want to add?
> Options:GoodYeast")
>         #Here I want to call this instace of GoodYeast from yeast_cell.py
>
>
>         print "Please place this yeast cell using an m,n point"
>         print "The upper left hand corner is (0,0)"
>         i = int(raw_input("Please enter a m value for the yeast cell."))
>         j = int(raw_input("Please enter a n value for the yeast cell."))
>
>         new_world[i,j] = YEAST
>         for j in range(N):
>             for i in range(M):
>                 world[i,j]=new_world[i,j]
>
>         counta = counta+1
>
>     print_world(small_world)
>
>
> ##################################
> #The following code gets the state of the world and determines
> #what is next to each cell, sensing
> #################################
>
> def get_state(world,i,j):
> #Returns the state of the cell at position (i,j)
>     return world.get((i,j), EMPTY)
>
> def count_neighbors(world,i,j):
> #Returns the number of cells next to this one
>     live_count = 0
>     for i_delta in [-1,0,1]:
>         for j_delta in [-1,0,1]:
>             if(i_delta,j_delta)==(0,0):
>                 continue
>             if get_state(world, i+i_delta, j+j_delta)==YEAST:
>                 live_count+=1
>     return live_count
>
> def is_grouped(world,i,j):
> #Returns a true value if the cell at (i,j) is connected by 1-8 others
>     return(get_state(world,i,j)==YEAST and
>            (1 <=count_neighbors(world,i,j)<=8))
>
> def next_world(world):
> #Shows which yeast are in a group using Q
>     M,N = world['dimensions']
>     new_world=copy.copy(world)
>     for j in range(N):
>         for i in range(M):
>             if is_grouped(world,i,j):
>                 new_world[i,j] = GROUP
>         for j in range(N):
>             for i in range(M):
>                 world[i,j]=new_world[i,j]
>
> def AddYeast():
>     print "If you selected 0 for your percolation you may now add
> yeast to the world."
>     print "The upper left hand corner is point (0,0)."
>     zz = raw_input("Do you want to add a yeast cell? y or n")
>     if zz == "y":
>         add_yeast(small_world)
>
>     elif zz == "n":
>         print_world(small_world)
>
>     raw_input("Please press return to group your yeast cells.")
>
> #####################################################
> #This is where the PD portion of the program starts
> #####################################################
>
> def PD_yeast():
>     print textwrap.fill ("The PD will added later in the OOP version")
>     print"REFERENCES"
>     print textwrap.fill ("Learning to program. By Alan Gauld")
>     print textwrap.fill ("How to Think Like a Computer Scientist. By
> Downey, Elkner, and Meyers")
>     print textwrap.fill("Cooperation amoung Microorganisms. Wingreen
> and Levin.")
>     print textwrap.fill ("Synthetic cooperation in engineered yeast
> populations. Shou, Ram, and Vilar")
>     print textwrap.fill ("Evolution in group-structured populations
> can resolve the tragedy of the commons. Killingback, Bieri, and
> Flatt")
>
>
> ###############################################################################
> #Start of program
>
> ###############################################################################
>
>
>
> raw_input("Please press return to start the program.")
>
> perc = raw_input("Please enter a thresold between 0-1 for the
> population.")
> perc = float(perc)
>
>
> n = int(raw_input("Please enter a n dimension.   "))
> m = int(raw_input("Please enter a m dimension.   "))
>
>
> small_world = random_world(m,n)
>
> print_world(small_world)
>
> AddYeast()
>
> next_world(small_world)
> print_world(small_world)
>
> print "Q indictates that the yeast cells found a group."
> print
> print
> print "Please press return to start the PD program."
> print
> print
>
>
> PD_yeast()
>
>
> yeast_cell.py
> ###############################################################
> #yeast_cell.py
> #Contains the different types of yeast behavior
> #By Ara Kooser
> ###############################################################
>
>
> #0 = cooperate
> #1 = defect
>
>
> class GoodYeast:
> #Cooperates all the time
>     YEAST = 'G'
>     #Should change generic variable @ in the world to G???
>     def __init__(self,name):
>         self.name = name
>         currency = 0
>         location = []
>
>     def response(self):
>         return 0
>
>     def location(world,i,j):
>         return world.get(i,j)
>         #I believe this allows the cell to know it's coordinates
>
>
> --
> Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis
> an sub cardine glacialis ursae.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070912/744c4289/attachment-0001.htm 


More information about the Tutor mailing list