[Tutor] calling class instances in functions

Ara Kooser ghashsnaga at gmail.com
Wed Sep 12 05:12:59 CEST 2007


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.


More information about the Tutor mailing list