Refer to own class in a static method
在静态方法中,是否有一个引用自己类的简写?
假设我有这段代码:
1 2 3 4 5 6 7 8 9 | class SuperLongClassName(object): @staticmethod def sayHi(): print 'Hi' @staticmethod def speak(): SuperLongClassName.sayHi() # Is there a shorthand? |
是的,使用
1 2 3 4 5 6 7 8 9 | class SuperLongClassName(object): @classmethod def sayHi(cls): print 'Hi' @classmethod def speak(cls): cls.sayHi() |
你可能想要一个
1 2 3 4 5 6 | class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(object): @classmethod def foo(cls): print cls.__name__ Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Claaa... |
警告:
1 2 3 4 5 | class Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass( Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass): pass Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Subclaaa... |
或者,在模块级别为类定义一个较短的别名:
1 2 3 4 5 6 7 8 9 | class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2(object): @staticmethod def foo(): return _cls2 _cls2 = Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2 # prints True print (Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2 is Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2.foo()) |