I
Inyeol Lee
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;
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;
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
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;
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;
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