[Tutor] method, type?
Steven D'Aprano
steve at pearwood.info
Wed Jan 6 20:00:22 EST 2016
On Thu, Jan 07, 2016 at 12:06:17AM +0000, Alan Gauld wrote:
> On 06/01/16 23:00, Cameron Simpson wrote:
>
> >>> ... ensures that if you subclass the class, you automatically
> >>> get a valid constructor as well.
> >>
> >> Wouldn't it return an instance of the superclass rather than
> >> the sub class? You'd need to override it wouldn't you?
> >
> > No, when you call:
> >
> > SubClass.from_blah(...)
> >
> > where from_blah is defined in the superclass, the leading "cls" parameter is
> > the subclass because you invoked it through the subclass,
>
> Yes, but my point is that constructors by their nature tend
> to be very specific.
That surely depends on the class.
> For example a constructor that fetches data from a database
> will embed a SQL query that is table specific and so may be
> completely wrong for a sub class (unless it somehow shares
> the superclass's table).
How many classes fetch data from a database? I accept that your
experience may be different from mine, but my experience tells me that
this is pretty unusual.
In any case, if the alternate constructor calls the default constructor,
you may only need to override the default, not both.
The point is that while it is true that the alternate constructors *may*
need to be overriden, sometimes they don't if you write them well. But
if you use a global, top-level factory function, you have little choice
but to create a separate factory function for every subclass.
I suppose you might make the class an explicit argument of the factory:
def factory(x, y, z, theclass=Spam):
return theclass(x+y+z)
but a class method seems more natural for Python.
--
Steve
More information about the Tutor
mailing list