[Zope] Subclassing Confusion

Michel Pelletier michel@digicool.com
Wed, 19 Jan 2000 15:34:34 -0500


> -----Original Message-----
> From: James W. Howe [mailto:jwh@allencreek.com]
> Sent: Wednesday, January 19, 2000 1:20 PM
> To: zope@zope.org
> Subject: [Zope] Subclassing Confusion
> 
> 
> I just tried to create a Python Base class for the purpose of 
> overriding 
> Images __str__ method and things didn't quite work as I would have 
> expected.  I subclassed Image as follows (using the 
> Renderable product as 
> an example):
> 
> import Acquisition
> from OFS import Image

You don't need these things...

> class RenderableImage:
>      def __str__ (self):
> 	Request = self.REQUEST
> 	if Request:
> 	    try:
> 		Method = getattr (self, 'render')
> 	    except AttributeError:
> 		return Image.__str__(self)
> 	    return Method (self, Request)
> 	else:
> 	    return "Renderable error: no request"
> 
> I defined a __init__ method to make the class a base class. 

You don't need to define an __init__.
 
> I then went 
> into my Product and create a new ZClass which used 
> RenderableImage as a 
> base class.  Since I was just testing things, I immediately 
> went and tried 
> to create a new instance.  No problem creating the object.  
> The problem (or 
> my confusion) was the fact that my RenderableImage didn't 
> inherit any of 
> the views which an Image would normally have (i.e. Edit, Upload, 
> Properties, View, Security).  My question is why didn't they 
> show up?

Because you didn't actually subclass anything?

> class RenderableImage:
                       ^^^^^
                       no declared subclasses....
>      def __str__ (self):

> I 
> would have thought that absent any other changes to my Image 
> subclass, that 
> the default Image views would show up as the views of my new ZClass.

I think you're doing this a bit wrong, but that's understandable, it's
not documented anywhere.

Create a new Product in your lib/python/Products dir called
'MyImageProduct'.

In that Product, create a module called 'MyImageModule.py'

In that module, create

class MyImageClass:

  def __str__(self):
    return self.id         # whatever...

In the Product, create an __init__.py file:

import MyImageModule

def initialize(context):
  context.registerBaseClass(MyImageModule.MyImageClass)


Now, your ZClasses can subclass (aka, mix-in) the MyImageClass.  You
don't need to subclass Acquisition or Image at the Python level, just
create ZClass that subclasses both Image and  MyImageClass.  The ORDER
in which you subclass is important, because BOTH the Image and your
MyImageClass define an __str__ method, you want to subclass Image first,
then MyImageClass.

-Michel