[Tutor] Class inheritance: is the kid calling? or the mom ??
pan at uchicago.edu
pan at uchicago.edu
Wed Dec 10 09:33:59 EST 2003
I have a class which needs calling itself in a function:
class Mom(object):
def __init__(self):
...
def oldfunc(self): # line [1]
...
self.someAttr = Mom()
Now, I make a new class out of it, added some new functions:
class Kid(Mom):
def __init__(self):
Mom.__init__(self)
...
def newfunc(self):
...
Then:
mom = Mom()
mom.oldfunc() # this will asign a new Mom() to mom.someAttr
mom.someAttr.oldfunc() # ok
Now:
kid = Kid()
kid.newfunc() # ok
kid.oldfunc() # this will asign Mom() to kid.someAttr
kid.someAttr.oldfunc() # ok
kid.someAttr.newfunc() # not ok ... because kid.someAttr is a Mom,
# which doesn't have newfunc().
To make this works, the oldfunc() is recoded as:
class Mom(object):
def __init__(self):
...
def oldfunc(self): # line [1]
...
self.someAttr = self.copy() # line [2] (copy() is pre-defined)
But this slows down the operation by ~ 10 fold.
Is there anyway that a class method can know who is calling it ---
the kid or the mom ? If yes, then we can do :
class Mom(object):
def __init__(self):
...
def oldfunc(self): # line [1]
...
if called_by_Mom:
self.someAttr = Mom () # line [3]
else:
self.someAttr = Kid() # line [4]
or even better, in generalized manner:
class Mom(object):
def __init__(self):
...
def oldfunc(self): # line [1]
...
self.someAttr = any_class_that_is_calling_me() # line [5]
Is this possible ????
thx.
pan
More information about the Tutor
mailing list