Question about instance creation

Joshua Macy amused at webamused.com
Mon Mar 20 21:01:57 EST 2000


Robin Barendregt wrote:
> 
> My problem is as follows:
> I'm fooling around with wxPython and want to instantiate objects
> (wxButton, wxFileDialog, etc....) and drop them on a canvas...kinda
> like a visual programming editor. With every object I associate a
> rectangular shape (to make it easier to show when the objects are
> selected and when connections between objects are made). There are a
> gazillion different classes of those objects and didn't want to
> subclass them all. That's why I wanted a derived class with changing
> base class.
> 

  It sounds like you may be trying to do too much with inheritance.  In
this case, composition would probably be more straightforward. You can
take advantage of the fact that in Python, you can assign new attributes
(ones not defined in the class) to an object on the fly to add a member
to each of the wx objects by which you can access the common behavior
you've defined in the rectangular shape class.  The following code
illustrates the technique, including saving a reference to the master
object within the sub-object in case you need to access any of the
master object's attributes:

class Composer:
    def __init__(self, master):
        self.master = master
        
    def update(self):
        print "In Composer.update Master.test =", self.master.test

class Test:
    def __init__(self):
        self.test = 1

    def write(self):
        print "Test.write"


if __name__ == "__main__":
    t = Test()
    c = Composer(t)
    t.compose = c
    t.write()
    t.compose.update()


Imagine that Test is one of the wx Classes, and you can see that as long
as you're willing to put up with a little indirection, you can add
arbitrary behavior to them, on an object-by-object basis.  Actually,
since the new attributes could just as well contain functions, you could
eliminate the indirection, at the cost of having the functions share no
common state information.


 Joshua



More information about the Python-list mailing list