[Tutor] Class Nesting

Steven D'Aprano steve at pearwood.info
Tue Feb 7 08:48:34 CET 2012


On Mon, Feb 06, 2012 at 08:17:05PM -0500, Greg Nielsen wrote:
[...]
>      So here is the problem, to create an object, you need to assign it to
> a variable, and you need to know what that variable is to call upon it
> later, so to have a object build a second object, it would need to somehow
> create a variable name, and you would somehow have to know what name it
> picked. Unless perhaps you had a Star Cluster list which had all of your
> created Star System objects, each with their own list of Planets which you
> could use list to call upon maybe....

Yes, that's exactly the way to do it. Rather than assigning each object to 
a name:

cluster1 = StarCluster()
cluster2 = StarCluster()
...


you can work with a list of clusters:

clusters = [StarCluster(), StarCluster(), ...]


You can then operate on then one at a time. Say you want to do something to
the 3rd cluster. Remembering that Python starts counting positions at zero,
you would write something like:

clusters[2].name = "Local Cluster 12345"  # give the cluster a name

If your StarCluster objects are mutable (and if you don't know what that 
means, don't worry about it, by default all classes are mutable), you can 
grab a temporary reference to a cluster while working on it:

for cluster in clusters:  # work on each one sequentially
    if cluster.stars == []:
        print("Cluster %s has no stars." % cluster.name)

Here I have assumed that each cluster is given a list of stars. Something 
like this:

class StarCluster(object):
    def __init__(self):
        self.name = "no name yet"
        self.stars = []
    def add_star(self, *args, **kw_args):
        self.stars.append(Star(*args, **kw_args))


Here I have given the StarCluster a method, "add_star", which takes an arbitrary 
set of arguments, passes them on to the Star class, and adds the resultant 
star to the list.

class Star(object):
    def __init__(self, name="no name yet", kind="red giant", planets=None):
        if planets is None:
            planets = []
        self.planets = planets
        self.name = name
        self.kind = kind


sol = Star(
    "Sol", "yellow dwarf", 
    ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 
         'Uranus', 'Neptune']  # ha ha, Pluto can bite me
    )
    

I hope this helps,



-- 
Steven



More information about the Tutor mailing list