Reputation: 3410
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
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
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