MightyPork
MightyPork

Reputation: 18901

Reference class from @staticmethod

↑↑↑ It does NOT

Let's say I have a class with some utility methods:

class Utils:
    @staticmethod
    def do_stuff():
        # some stuff
        Utils.do_other_stuff()
        # some more stuff

    @staticmethod
    def do_other_stuff():
        # somehting other

I don't really like the Utils.do_other_stuff() part.

If it was instance method, I would reference it via self, but here I have to write the full class name.

Is this where @classmethod is a good idea to use, or is it overkill? - or is there some cleaner way to write Utils, perhaps with a module?

Upvotes: 0

Views: 66

Answers (3)

daveoncode
daveoncode

Reputation: 19618

@classmethod is the way to go:

class Utils:
    @classmethod
    def do_stuff(cls):
        # some stuff
        cls.do_other_stuff()
        # some more stuff

    @classmethod
    def do_other_stuff(cls):
        # somehting other

Just a clarification related to Martijn Pieters comment: I usually avoid @staticmethod and I prefer to adopt always @classmethod because it allows me to refer to the class and its methods. (I don't agree with suggestions about writing modules with functions… I'm an OOP supporter :P)

Upvotes: 2

user2357112
user2357112

Reputation: 282158

It doesn't look like Utils will ever be subclassed or instantiated; it's just a wrapper for static methods. In that case, these methods can all be turned into module-level functions, perhaps in a separate utils module:

# No class!
def do_stuff():
    ...
    do_other_stuff()
    ...

def do_other_stuff():
    ...

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1125398

If you need a reference to the current class (which could be a subclass), then definitely make it a classmethod.

That's not overkill; the amount of work Python does to bind a class method is no different from a static method, or a regular method for that matter.

However, don't use classes here unless you have to. Python is not Java, you do not have to use a class and functions can live outside of classes just fine.

Upvotes: 2

Related Questions