quickshiftin
quickshiftin

Reputation: 69581

Python refer to class from within class

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()

Upvotes: 0

Views: 818

Answers (3)

kindall
kindall

Reputation: 184081

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.

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208405

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.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121346

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.

Upvotes: 1

Related Questions