[Tutor] method could be a function warning
Cameron Simpson
cs at cskk.id.au
Wed Dec 22 20:46:09 EST 2021
Just to follow up to myself:
On 23Dec2021 12:22, Cameron Simpson <cs at cskk.id.au> wrote:
>A function outside a class is a general purpose utility function. I
>don't have many static methods, but those which are are conceptually
>related to the class. Here's an example from my Tag class:
>
> @staticmethod
> def is_valid_name(name):
> ''' Test whether a tag name is valid: a dotted identifier.
> '''
> return is_dotted_identifier(name)
>
>So there's a Tag.is_valid_name(name) method for checking that a tag name
>is valid. It doesn't use the class or instance, but how it is
>implemented is a direct feature of the class. So it is a static method.
So what we're getting from a class staticmethod is that the class name
is effectively part of the the function name. Instead of maybe making an
external function like:
def is_valid_tag_name(name):
I've defined a function effectively named "Tag.is_valid_name". Which is
quite explicit about what kind of validity it is testing.
Also, if you've subclasses, or are writing something else which works on
"tag-like" things, you can call:
if tag_like_thing.is_valid_name(some_name):
and it will get the appropriate is_valid_name() method from the class
which implements tag_like_thing, which might not be my "Tag" class but
something which works like it.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list