HOWTO restrict multiply inherited class to on sub-class

Duncan Booth duncan at rcp.co.uk
Mon Apr 2 12:08:22 EDT 2001


Michael Hudson <mwh21 at cam.ac.uk> wrote in 
<m37l13b9nj.fsf at atrus.jesus.cam.ac.uk>:

>Michael Hudson <mwh21 at cam.ac.uk> writes:
>
>> > any clues, anyone?
>> 
>> Try this:
>
>Or, on second thoughts, don't.  It will call Base1's methods even if
>they're overridden in Derived, something you almost certainly don't
>want.

How about this version:

=== cast.py ===
class Casted:
    def __init__(self, wrapped, klass):
        self.__wrapped = wrapped
        self.__klass = klass
    def __getattr__(self, attr):
        if hasattr(self.__klass, attr):
            return getattr(self.__wrapped, attr)
        else:
            raise AttributeError, \
               ("%s instance has no attribute %s" % (`self.__klass.
__name__`, `attr`))

def cast(inst, klass):
    return Casted(inst, klass)

if __name__=='__main__':
    class Base1:
        def foo(self):
            return "Base1 foo"

    class Base2:
        def bar(self):
            return "Base2 foo"

    class Derived(Base1, Base2):
        def foo(self):
            return "Derived foo"

    print "Acessing foo, bar, zzz in Derived"
    d = Derived()
    print "foo", d.foo()
    print "bar", d.bar()
    try:
        print "zzz", d.zzz()
    except AttributeError, v:
        print "AttributeError", v

    print "Acessing foo, bar in Derived cast to Base1"
    c = cast(d, Base1)
    print "foo", c.foo()
    try:
        print "bar", c.bar()
    except AttributeError, v:
        print "AttributeError", v

    print "Acessing foo, bar in Derived cast to Base2"
    c = cast(d, Base2)
    try:
        print "foo", c.foo()
    except AttributeError, v:
        print "AttributeError", v
    print "bar", c.bar()

    # Casting a Base1 to a Base2 should give us no callable methods.
    print "Acessing foo, bar in Base1 cast to Base2"
    c2 = cast(Base1(), Base2)
    try:
        print "foo", c2.foo()
    except AttributeError, v:
        print "AttributeError", v
    try:
        print "bar", c2.bar()
    except AttributeError, v:
        print "AttributeError", v
=== end of cast.py ===




More information about the Python-list mailing list