[Tutor] Re: Class in a class

Andrei project5 at redrival.net
Fri Feb 18 09:37:37 CET 2005


Luis N <tegmine <at> gmail.com> writes:

> Does it make sense to do this:
> 
> In [2]: class AB:
>    ...:     pass
> In [3]: a = AB()
> In [4]: a
> In [5]: class BC:
>    ...:     def __init__(self, foo):
>    ...:         self.foo = foo
> In [6]: b = BC(a)
> In [7]: b.foo

This case is not that different from what you probably already do in classes,
given the fact that all attributes are objects anyway. Compare the following two
classes which have pretty much identical structure:

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        # x and y would be simple floats, but nothing
        # stops you from using more fancy attributes,
        # like in the Line class below

class Line(object):
    def __init__(self, point1, point2):
        self.points = [point1, point2]
        # note how self.points is a complex
        # data structure (list object)!

Certainly if we can use standard objects like floats, lists or dictionaries as
attributes, we can also use objects of our own design:

class Triangle(object):
    def __init__(self, line1, line2, line3):
        self.lines = [line1, line2, line3]
        self.points = []
        for line in self.lines:
            for point in line.points:
                if point not in self.points:
                    self.points.append(point)

And you could go even higher, to a tetraeder made out of triangles, if you
extended Point to also allow z coordinates.

Andrei



More information about the Tutor mailing list