group several methods under a attribute

Aaron Brady castironpi at gmail.com
Mon Apr 6 13:30:44 EDT 2009


On Apr 6, 12:02 pm, Aaron Brady <castiro... at gmail.com> wrote:
> On Apr 6, 5:40 am, jelle <jelleferi... at gmail.com> wrote:
>
> > Hi,
>
> > I'm working on a pretty large class and I'd like to group several
> > methods under a attribute.
> > Its not convenient to chop up the class in several smaller classes,
> > nor would mixins really solve the issue.
> > So, what is a pythonic way of grouping several methods under a
> > attribute?
>
> > Many thanks in advance,
>
> > -jelle
>
> Hi jelle,
>
> I disagree with Gerhard that you 'should find a better way' and
> another way 'almost certainly the right thing', unless his reason is
> merely that it's an advanced technique that will get you into problems
> down the road.
snip
> class ClsA( object ):
>     def __init__( self ):
>         self.inst= None
>     def __get__( self, instance, owner ):
>         self.inst= instance
>         return self
snip

There's a potential conflict in the above, which may have contributed
to Gerhard's advice.

If you have:

bA= ClsB( )
bB= ClsB( )
bA.A.submethA( 'what' )

then the ClsA instance will think it's being accessed from 'bA' until
it's accessed again!  This may cause problems such as if you store a
reference to it, because bB could access it, and it won't think it's
being accessed from bA anymore.  To get around this, you probably want
'__get__' to create a new object that is specifically dedicated to the
instance of ClsB that's calling it.  bA.A and bB.A return new objects,
separate from each other.  However, then two calls to bA.A won't
return the same object; they'll return new every time.

Another detail is that ClsA can't store instance information.  It
should be stored in ClsB instances, and the methods merely go
somewhere else.  Otherwise, the right place for 'A= ClsA( )' is in the
constructor:

class clsB:
  def __init__( self ):
    self.A= ClsA( )

Then, every ClsB instance has its own instance of ClsA, and it can
store instance information, and doesn't create new instances when you
call it.  The creation of 'ClsA' merely goes in the initializer, not
the class statement.



More information about the Python-list mailing list