python's OOP question

Bruno Desthuilliers onurb at xiludom.gro
Mon Oct 16 09:01:41 EDT 2006


neoedmund wrote:
> Bruno Desthuilliers wrote:
>> neoedmund wrote:
>> (*PLEASE* stop top-posting - corrected)
>>> Ben Finney wrote:
>>>> [Please don't top-post above the text to which you're replying.]
>>>>
>>>> "neoedmund" <neoedmund at gmail.com> writes:
>>>>
>>>>> I'm trying to achieve a higher level of "reusability". Maybe it
>>>>> cannot be done in python? Can anybody help me?
>>>> What, specifically, are you trying to achieve? What problem needs
>>>> solving?
>>> python use multiple inheritance.
>>> but "inheritance" means you must inherite all methods from super type.
>>> now i just need "some" methods from one type and "some" methods from
>>> other types, to build the new type.
>>> Do you think this way is more flexible than tranditional inheritance?
>>>
>> While dynamically adding attributes (and methods - which are attributes
>> too) is not a problem, I'd second Gregor's anwser : it might be better
>> to use composition/delegation here.
>> 
> Could you show some code to help me know how composition/delegation can
> be done here? Thanks.

About composition/delegation, there's no "one-size-fits-all" answer, but
the main idea is to use the magic '__getattr__(self, name)' method.

Now back to your specific case : after a better reading of your original
question, straight composition/delegation wouldn't work here - at least
not without modifications to both C1 and C2 (sorry, should have read
better the first time).

Given the context (ie : "create a new type with methods from type X and
methods from type Y"), a very simple solution could be:

class C3(object):
    m = C2.m.im_func
    v = C1.v.im_func

FWIW, if you have full control over C1, C2 and C3, you could also just
'externalize' the functions definitions:

def v1(self, o):
    return "expected "+o

def v2(self, o):
    return "unexpected "+o

def m2(self):
    """ requires that 'self' has a v(self, somestring) method """
    print self.v("aaa")

class C1(object):
    v = v1

class C2(object):
    v = v2
    m = m2

class C3(object):
    v = v1
    m = m2


The problem (with the whole approach, whatever the choosen technical
solution) is that if one of theses methods depends on another one (or on
any other attribute) that is not defined in your new class, you're in
trouble. This is not such a big deal in the above example, but might
become much more brittle in real life.

Now we can look at the problem from a different perspective. You wrote:
"""
but "inheritance" means you must inherite all methods from super type.
now i just need "some" methods from one type and "some" methods from
other types, to build the new type.
"""

What is your problem with having the other extra methods too ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list