class attribute to instance attribute
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

class attribute to instance attribute

From: Donnal Walter <donnal@donnal.net>
Date: Thu Jun 30 2005 - 22:50:26 CEST

This is a question about Python patterns or idioms. Over a period of
time, I have evolved a pattern of usage that seems to work better for me
than other ways I tried previously, but in writing some documentation I
don't know what to call this syntax or how best to describe it. I have
not seen it used in other places.

The somewhat longish version is that I have implemented an MVP
(model-view-presenter) architecture where each "presenter" has a "view"
as an attribute. Take the TextField and Frame presenters for example.
Here is one way to do it:

import wx
class TextField:

     def __init__(self):
         # do some things here to calculate *args
         self.view = wx.TextCtrl(*args)
         # do more things to set up the view

     # and more methods to make this a presenter

class Frame:

     def __init__(self):
         # do some things here to calculate *args
         self.view = wx.Frame(*args)
         # do more things to set up the view

     # and more methods to make this a presenter

There are a number of presenters, some of which have the same type of
view (TextField and NumberField, for example) and many of which have
different views (Frame and Notebook, for example). The way I have chosen
to do this is to put the logic in one superclass, "Presenter":

class Presenter:
     view = None

     def __init__(self):
         # do some things here to calculate *args
         # if view is class, create instance
         if callable(self.view):
             self.view = self.view(*args)
         # do more things to set up the view

     # and more methods to make this a presenter

class TextField(Presenter):
     view = wx.TextCtrl

class Frame(Presenter):
     view = wx.Frame

Then:
>>> app = wx.App(False)
>>> f = Frame()
>>> isinstance(f.view, wx.Frame)
True

To summarize, each subclass has a class attribute "view" that is
converted to an instance attribute of the same name at runtime.

Is this a common Python idiom? If so, does it have a name? Is there a
better way to do the same thing?

Regards,
Donnal Walter
Arkansas Children's Hospital
Received on Thu Sep 29 16:40:32 2005