RE: list.sorted()

From: Robert Brewer (fumanchu_at_amor.org)
Date: 12/07/03


Date: Sat, 6 Dec 2003 16:59:54 -0800
To: <python-list@python.org>

Douglas Alan wrote:
> "Robert Brewer" <fumanchu@amor.org> writes:
>
> > I've been looking through my code and can't find a single case where
> > I declared a classmethod, then called it from an instance, as in the
> > above example. Are there any cases where this is useful?
>
> Yes, it is useful. I don't know if I've made use of this feature yet
> in Python, but I do know that I was bent out of shape when I realized
> that C++ doesn't support "virtual static functions" (because I would
> have liked to use them.
...
> These functions are used in a parser that parses text representations
> of objects in the class hierarchy. isLegalFieldTag() is used by the
> parser to hlep determine whether or not a token it has just read is a
> legal token.

For example, whether "hlep" is a legal token? ;)

> The reason why I wanted it to be a static function is
> that whether or not a token is legal does not depend on a particular
> instance -- only on the class of the instance. On the other hand, in
> order to do the parsing, I do need to dispatch based on the class of a
> particular instance.
>
> I suppose, unlike in C++, in Python I could fetch the class of the
> instance, and then dispatch on that, but that might be a bit
> more cumbersome.

Ah, thanks. By "more cumbersome" are you talking simply about having to
add .__class__ as in:

    anObject.__class__.foo()

...or is there more to it?

I would probably implement your example by making isLegalFieldTag a
plain ol' instance method. To take a trivial case:

    class Tag(object):
        legal = True
        def isLegalFieldTag(self):
            return self.legal

If self hasn't defined "legal" then it is resolved via the class. I'm
sure your logic was more complex, but that's the route I tend to take.

Note that I'm not thinking about barring *all* class access from
instances, just those methods explicitly made 'classmethods', which
expect cls as a first parameter.

Robert Brewer
MIS
Amor Ministries
fumanchu@amor.org



Relevant Pages

  • Re: More __init__ methods
    ... Different behaviours should be in different functions. ... instance method inside the classmethod. ... but if I use this @classmethod style to simplify the ...
    (comp.lang.python)
  • Re: classmethod & staticmethod
    ... Not necessarily - you can access class attributes from within an ... instance method (but obviously a classmethod cannot access instance ... Neil Cerutti ...
    (comp.lang.python)
  • Re: new-style classes and len method
    ... the meaning of "classmethod", thinking of it as an instance method. ... class object, such a confusion is not so surprising!-) ...
    (comp.lang.python)
  • Re: new-style classes and len method
    ... I was misunderstanding ... the meaning of "classmethod", thinking of it as an instance method. ...
    (comp.lang.python)