building embedded classes as in C/C++
Markus Stenberg
mstenber at cc.Helsinki.FI
Wed Aug 4 00:53:34 EDT 1999
Andy Beall <beall at psych.ucsb.edu> writes:
> 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!
You did not pay attention, however; you set _class_wide_ variables, global
to all instances (pos, ang). Thus, the behavior was to be expected.
Try this instead:
class Object:
def __init__(self):
self.pos = Point()
self.ang = Point()
>
> -------------------------------------------------------------------------
> 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).
> -------------------------------------------------------------------------
--
"If you want to travel around the world and be invited to speak at
a lot of different places, just write a Unix operating system."
-- Linus Torvalds
More information about the Python-list
mailing list