[Tutor] Question About Structs

dman dsh8290@rit.edu
Fri, 22 Feb 2002 13:39:10 -0500


On Fri, Feb 22, 2002 at 01:39:35PM -0300, Hector A. Paterno wrote:
| Hi, Im recently programming in python and I'v one question :
| 
| Who is the best form in python to replace what in c is called struct ?
| 
| For example in C I have this struct :
| 
| struct monitor {
|  char *model;
|  int number;
| };
|    
| My best was to replace this with a DIC :

A dict will work, but often times a class is better.  For example :

class monitor :
    def __init__( self , model , number ) :
        self.model = model
        self.number = number


Then you can create a monitor like :

m = monitor( "The Model" , 230 )
print m.model , m.number


Attribute access on instance objects is just like member access in C
(apart from not needing the derefence operator for pointer-to-struct). 

| Pd: Python doesn't has the case statment ?

Instead use something like :

# first define functions for the operations we want to take place
def f1() :
    print "f1"

def f2() :
    print "f2"


# define the jump table, note that any hashable object can be the key,
# not just 'int' or 'char'
switch = { 1 : f1 , 2 : f2 }


Notice how functions are objects, just like anything else.  The
counterpart in C is a pointer-to-a-function.  It is this "pointer to a
function" that is the value part of the dictionary.

# now here we do our "switch"
# first get the data to switch on
which_op = input( "Enter a choice, 1 or 2 : " )
# now lookup the "case block"
the_op = switch[ which_op ]
# call the function
the_op() 

HTH,
-D

-- 

The fear of the Lord leads to life:
Then one rests content, untouched by trouble.
        Proverbs 19:23