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? 
1

2 Answers 2

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() 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.