building embedded classes as in C/C++

Dirk-Ulrich Heise hei at adtranzsig.de
Wed Aug 4 03:05:38 EDT 1999


Python has no member variable declarations.
You create your member variables in a constructor.
Try this (didn't try it, hope there's no typo):

class Point:
  def __init__(self):
    self.x = 0

class Object:
  def __init__(self):
    self.pos = Point()
    self.ang = Point()
obj1 = Object()
obj2 = Object()

obj1.ang.x = 123

print obj2.ang.x

--
Dirk
Where did you want to go again?
Andy Beall schrieb in Nachricht <37A78579.9856D16 at psych.ucsb.edu>...
>Hi,
>
>I'd like to build an embedded structure (Python class) much like I do in
>C if possible.  When I do the following, multiple instances of my final
>class overwrite each others sub-class values!
>
>-------------------------------------------------------------------------
>class Point:
> x = 0
> y = 0
> z = 0
>
>class Object:
> pos = Point()
> ang = Point()
>
>
>obj1 = Object()
>obj2 = Object()
>
>obj1.ang.x = 123
>
>print obj2.ang.x    <<-- AND I FIND IT CONTAINS OBJ1's X VALUE
>-------------------------------------------------------------------------
>
>
>
>In C, this would be:
>
>-------------------------------------------------------------------------
>typedef struct Point {
> float  x;
> float  y;
> float  z;
>} Point;
>
>typedef struct Object {
> Point  pos;
> Point  ang;
>} Object;
>
>Object obj1;
>Object obj2;
>
>obj1.ang.x = 123;
>printf("%f", obj2.ang.x);   <<-- AND NOW THE VALUES IN OBJ1 AND OBJ2
> WILL NOT BE RELATED (OBJ2 WILL JUST
> CONTAIN GARGAGE AT THIS POINT).
>-------------------------------------------------------------------------
>
>
>I've found that writing something like:
>
>class Object(Point):
> ...
>
>works, but then I don't have a wrapper around the (x, y, z) values
>anymore and I
>don't know how to bring in Point more than once. Is it possible to do
>this in Python.  I've looked in the tutorial and Mark Lutz's book to no
>avail.
>
>Thanks,
>Andy Beall






More information about the Python-list mailing list