0

I've become aware of @staticmethod - next question, are you supposed to use the class name to refer to these methods from within the class?

class C:
    @staticmethod
    def imstatic():
        print("i'm static")

    @staticmethod
    def anotherstatic():
        # Is this the proper python way?
        C.imstatic()

    @staticmethod
    def brokenstatic():
        # This doesn't work..
        self.imstatic()
3
  • Did you try this? The answer should be pretty self evident, but yes. Commented Nov 22, 2013 at 22:34
  • Well the reason I asked is because Java and PHP which I'm used to both have keywords for this... Commented Nov 22, 2013 at 22:35
  • 1
    Note that Python's static method is a different beast from Java and PHP static methods. Commented Nov 22, 2013 at 22:36

3 Answers 3

1

Yes, as you don't have any other reference to the class from within a static method. You could make these class methods instead, using the classmethod decorator:

class C:
    @staticmethod
    def imstatic():
        print("i'm static")

    @classmethod
    def anotherstatic(cls):
        cls.imstatic()

A class method does have a reference to the class.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I believe @classmethod is what I'm after. I've now found this thread and will keep reading.
1

If you need to refer to the class within a static method you should probably be using a classmethod instead:

class C:
    @staticmethod
    def imstatic():
        print("i'm static")

    @classmethod
    def imclass(cls):
        cls.imstatic()

In the same way that instance methods are "magically" given a reference to the instance as the first argument, class methods are given a reference to the class. You can call them either from an instance or from the class directly, for example both of the following are valid and have the same behavior:

C().imclass()
C.imclass()

That being said, if you do still want to use a static method your current approach is correct, just refer to the class by name.

1 Comment

Also, self is only used for instance methods.
1

If you always want to call the static method of that specific class, yes, you must specify it by name. If you want to support overriding the static methods, what you want is a classmethod instead: it passes the class on which the method is being called as the first parameter, analogous to self on regular instance methods, so you can call the overridden method. In general I'd suggest using classmethods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.