group several methods under a attribute

Aaron Brady castironpi at gmail.com
Mon Apr 6 13:02:20 EDT 2009


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.  There's nothing 'un-object-oriented' about it.  The
link to the God pattern alleges that it fails to 'divide and conquer',
but you are dividing.  I think Python opens some beautiful doors in
this regard.

Here is some code which I understand accomplishes what you sought.

class ClsA( object ):
    def __init__( self ):
        self.inst= None
    def __get__( self, instance, owner ):
        self.inst= instance
        return self
    def submethA( self, arg ):
        print( 'submethA %r, instance %r'% ( arg, self.inst ) )

class ClsB( object ):
    A= ClsA( )
    def methA( self, arg ):
        print( 'methA %r'% arg )

b= ClsB( )
b.methA( 'this' )
b.A.submethA( 'that' )

#Output:
'''
methA 'this'
submethA 'that', instance <__main__.ClsB object...>
'''

In Python 3, you don't need 'ClsA' and 'ClsB' to inherit from 'object'
explicitly.  If you call 'b.A' from a class, 'ClsB.A', you will get a
'ClsA' object with a None 'inst' attribute, which is a big hole
waiting for you to step in.  Perhaps you want a wrapper for your
methods of 'ClsA' to check that 'inst' is set, or merely throw an
exception in '__get__' if 'instance' is 'None'.  Python after all
requires that a method's first argument be an instance of an improper
subclass of the class it was defined for.




More information about the Python-list mailing list