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. 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). Similarly reading from a network it will only pull the fields necessary for the superclass from the message. Indeed the trigger message it sends to the server to initiate the transfer may well have the class details included. So although you might wind up with an object whose type is subclass, its details may be totally wrong or even fail to operate (if the table has no corresponding ID for example). It would certainly work for a few cases but I suspect most real-world constructors will fail unless overridden. Other class methods are much more likely to work OK. (For example those maintaining a cache of instances or simply keeping a count) I'm just dubious about constructors because they are so specific about where/how they obtain their data. (Unless you get very clever about how you use cls to access meta-data, or maintain some kind of config mapping (possibly as class attributes) to tell the constructor what to do. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor