Unification of Methods and Functions
David MacQuigg
dmq at gain.com
Fri May 28 14:36:55 EDT 2004
On 28 May 2004 08:10:46 GMT, Duncan Booth <me at privacy.net> wrote:
>David MacQuigg <dmq at gain.com> wrote in
>news:eu9cb0tkf674ob8u595sqk9kncs8nvm8k9 at 4ax.com:
>
>> To summarize our discussion on static methods, we have four ways to
>> accomplish the purpose of making a method callable without an
>> instance.
>>
>> 1) Add the staticmethod wrapper.
>> 2) Create a dummy instance, and use it to call the method.
>> 3) Move the method outside of the class, and if that disturbs the
>> modular structure of the program, make the class and its external
>> function a new module with its own namespace.
>> 4) Move the method outside of the class, but make sure it is still
>> "associated" with the class by giving it a special name.
>>
>> Is there any reason we *should not* use solution #1?
>
>You missed 5) Use a classmethod wrapper.
>
>The commonest reason I know of for wanting to a method callable without an
>instance is to provide the class with factory functions, and in that case
>you definitely don't want to use solution #1 as solution #5 gives you
>support for subclassing at no extra charge.
I haven't added any classmethod examples to my OOP chapter, because
until now I've thought of them as very specialized. I'm searching for
a good textbook example, but all I can find is trivially replacable
with an instance method or a static method. If you have an instance
already, the class can be resolved via self.__class__. If you don't
have an instance, the desired class can be passed as an argument to a
static method.
I sounds like you may have a good use case for classmethods. Could
you give us an example, and a brief explanation of what it does that
can't be done as easily with other method forms? Your help will be
greatly appreciated.
-- Dave
More information about the Python-list
mailing list