Overriding (factory?) methods and inheritance ...
Jp Calderone
exarkun at intarweb.us
Mon Dec 30 12:04:59 EST 2002
On Mon, Dec 30, 2002 at 04:43:35PM +0000, Rocco Rossi wrote:
> I posted a message yesterday about problems I was having when inheriting
> from base classes that contained methods (would it be correct to call them
> "factory" methods) which produced instances of the same class (type), like a
> RationalNumber class or a ComplexNumber class or Vector class, and so on.
>
> The inherited specialized class would of course have those same methods
> return values of the base class type, so that in the end one would not be
> able to exploit the new features of the inherited class for those values ...
> no code re-use!!!
>
> One way out, of course, (which was also suggested by Laotseu --- BTW
> thanks ---), would be to override precisely those methods, and like I said,
> we would be losing the benefits of object-oriented programming that way, but
> it certainly still is possible to let the base class do the majority of the
> work ... Has this problem ever come up before? It seems to me that it is
> non-trivial, but then again maybe I'm not confronting it in the appropriate
> manner. Need some help.
>
> Thanks.
>
I missed yesterday's post, but perhaps...
class Base:
def commonMethod(self, args):
self.variousThings(args)
return self.__class__(appropriateVariables)
or if your class is new-style...
class Base(object):
def commonMethod(self, args):
return type(self)(appropriateVariables)
or even...
class Base(object):
def __new__(klass, args):
if someCondition(args):
return FirstSubClass(args)
elif anotherCondition(args):
return SecondSubClass(args)
else:
return LastSubClass(args)
def commonMethod(self, args):
return Base(args)
The last is probably the least desirable since it is somewhat inflexible.
Jp
--
"There is no reason for any individual to have a computer in their
home."
-- Ken Olson, President of DEC, World Future Society
Convention, 1977
--
12:00am up 14 days, 9:45, 3 users, load average: 0.15, 0.25, 0.16
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20021230/6ab4605a/attachment.sig>
More information about the Python-list
mailing list