[Tutor] method, type?

Cameron Simpson cs at zip.com.au
Wed Jan 6 18:00:58 EST 2016


On 06Jan2016 18:57, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>On 06/01/16 14:46, Steven D'Aprano wrote:
>> It would be reasonable to make this a factory function declared in the
>> global module level. But I think making it a classmethod is better.
>
>I won't put up much of an argument here. In C++ or Java I'd
>definitely say use a class method. But it seems to me that I've
>seen more factory functions in modules than class method factories.
>But that's not been a detailed analysis just a gut feel for what
>seems idiomatic in Python. It also seems easier for beginners
>to grasp than the more esoteric notion of class methods.

Most of my factories are global functions, but that is mere historic artifact.  
As a direct consequence of explaining this to Alex Kleider I'm moving 
aggressively to using @classmethod for this, naming them ".from_*" unless I 
have some amazing reason not to.

>> ... 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, just as you get the 
leading "self" instance parameter when you invoke an instance method through 
the instance. That's one reason that @classmethod is so nice here.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list