c to python

David M. Cook davecook at nowhere.net
Tue May 27 02:07:05 EDT 2003


In article <mailman.1053970727.15498.python-list at python.org>, Jimmy verma
wrote:

> struct ab
> {
>         int a;
>         int b;
>         int *c;
>        struct d *d;
> } AB;
> 
> 
> And i am using it in my program like
> 
> void XYZ(int a , AB *b)

To simulate the in/out parameter b, you could use any mutable type.  You can
use dictionaries:

ab = {'a' : 5, 'b' : 6, 'c' : [1, 2, 3], 'd' :  d : {'foo' : 7, 'bar' : 8} }

Or just a list.  Since all built-in python containers can can be
heterogeneous, each of them can be useful substitutes for the different ways
in which structs are used in C.  

Also, instead of using a mutable type, you can use an immutable type like
tuple and just return a different tuple.

Objects have already been mentioned, but instead of doing

class AB:
      pass
      
And assigning attributes anywhere, I lean toward setting attributes in the
class body, so that someone else (you 6 months later; for me 1 week later ;}
) can see what attributes you intend this object to have, and how they are
intended to be used. You can also use default values:

class AB:
      def __init__(self, a=5, b=6, c=None, d=None):
      	  self.a = a
	  self.b = b
	  if c is None:
	     c = []
	  self.c = c
	  if d is None:
	     d = {}
	  self.d = d
	  

If you want to be more restrictive, you can use new style classes and
properties

http://www.python.org/2.2.2/descrintro.html#property

Dave Cook




More information about the Python-list mailing list