3

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?
arshajii
  • 127,459
  • 24
  • 238
  • 287
Derek Chiang
  • 3,330
  • 6
  • 27
  • 34
  • 6
    you should use a class method instead of a static method [more info here][1] [1]: http://stackoverflow.com/questions/9744223/python-difference-between-static-methods-vs-class-method – Francisco Meza Jul 11 '13 at 22:08

2 Answers2

10

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()
Alex MDC
  • 2,416
  • 1
  • 19
  • 17
5

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())
user2357112
  • 260,549
  • 28
  • 431
  • 505