Derek Chiang
Derek Chiang

Reputation: 3410

Refer to own class in a static method

Is there a shorthand for referring to its own class in a static method?

Say I have this piece of code:

class SuperLongClassName(object):

    @staticmethod
    def sayHi():
        print 'Hi'

    @staticmethod
    def speak():
        SuperLongClassName.sayHi()  # Is there a shorthand?

Upvotes: 3

Views: 1243

Answers (2)

Alex MDC
Alex MDC

Reputation: 2456

Yes, use @classmethod instead of @staticmethod. The whole point of @staticmethod is to remove the extra class parameter if you don't need it.

class SuperLongClassName(object):

    @classmethod
    def sayHi(cls):
        print 'Hi'

    @classmethod
    def speak(cls):
        cls.sayHi()

Upvotes: 10

user2357112
user2357112

Reputation: 280708

You probably want a classmethod. It works like a staticmethod, but takes the class as an implicit first argument.

class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(object):
    @classmethod
    def foo(cls):
         print cls.__name__

Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Claaa...

Warning:

class Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(
        Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass):
    pass

Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Subclaaa...

Alternatively, define a shorter alias for your class at module level:

class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2(object):
    @staticmethod
    def foo():
        return _cls2
_cls2 = Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2

# prints True
print (Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2 is
       Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2.foo())

Upvotes: 5

Related Questions