Problem with object-in-object and common superclass

Steffen Ries steffen.ries at sympatico.ca
Mon Sep 25 08:06:34 EDT 2000


ikaran at my-deja.com writes:

> Here's a quick program that demonstrates the
> problem:

[...]

> The command run ad infinitum is "print 'pea'"; the
> problem seems to be that the identifier "stuff"
> points to the same Python entity from within both
> "Pod" and "Plant."
> 
> Questions:
> 
> *  Am I making an obvious error in logic with my
> program structure that has nothing to do with
> Python?  One possibility, I suppose, is that I am
> accessing the "stuff" in "Pod" from "Plant," and
> hence I am "fooling" the interpreter into
> accessing the "Plant" namespace rather than the
> "Pod" namespace.  From an execution standpoint, is
> "Plant" the innermost scope?

The problem is that "stuff" is defined as a class variable in
"Container". As such it is shared by all instances of "Container" and
its subclasses. (Just to confuse you, you can access class variables
like instance variables, i.e. as "self.stuff". "Container.stuff" would
reference the same variable and make it clearer what's going on).

> *  If this is a common problem in Python
> programming, what is the canonical solution?

Not really a common problem, but the canonical solution is to make
"stuff" an instance variable, which is initialized in the constructor
of Container:

--8<----8<----8<----8<----8<----8<----8<----8<--
class Container :
    def __init__(self):              # add constructor
        self.stuff = []              # create instance variable
    def show(self) :
        for thing in self.stuff :
            if isinstance(thing, Container) :
                thing.show()
            else :
                print thing

class Pod(Container) :
    def __init__(self) :
        Container.__init__(self)     # must call constructor of superclass
        self.stuff.append("pea")

class Plant(Container) :
    def __init__(self) :
        Container.__init__(self)     # must call constructor of superclass
        self.stuff.append(Pod())

sprout = Plant()
sprout.show()
--8<----8<----8<----8<----8<----8<----8<----8<--

hth,
/steffen
-- 
steffen.ries at sympatico.ca	<> Gravity is a myth -- the Earth sucks!



More information about the Python-list mailing list