need help on sublcass and scope

Inyeol Lee inyeol.lee at siimage.com
Mon Dec 8 23:43:52 EST 2003


I'm an OOP newbie, and needs help on subclassing from different module.

I made a base module a.py which contains two classes C1 and C2;

## start of a.py

class C1(object):
    def m(self):
        print "method m in class C1 in module a"

class C2(object):
    def __init__(self):
        print "class C2 in module a"
        self.a = C1()
        self.a.m()

## end of of a.py

Then, I made another module b.py which extends this base module;

## start of b.py

import a

class C1(a.C1):
    def m(self):
        print "method m in class C1 in module b"
        a.C1.m(self)

class C2(a.C2):
    def __init__(self):
        print "class C2 in module b"
        a.C2.__init__(self)

## end of of b.py

When I instantiate C2, I get;

  >>> import b
  >>> i = b.C2()
  class C2 in module b
  class C2 in module a
  method m in class C1 in module a
  >>>

It doesn't use class C1 in module 'b', but uses C1 in module 'a' because
the last line in b.py 'a.c2.__init__(self)' runs with module scope a.
So I tweaked the C1 instantiation line in a.py from

        self.a = C1()

to

        import sys
        self.a = sys.modules[self.__module__].C1()

and got the result I expected;

  >>> import b
  >>> i = b.C2()
  class C2 in module b
  class C2 in module a
  method m in class C1 in module b
  method m in class C1 in module a
  >>>

but it looks like an ugly hack to me.
If there's common OOP idiom to handle this kind of problem, give me
some pointer.

Thanks,
Inyeol





More information about the Python-list mailing list