关于python:在静态方法中引用自己的类

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?


是的,使用@classmethod而不是@staticmethod@staticmethod的全部要点是,如果不需要额外的类参数,就删除它。

1
2
3
4
5
6
7
8
9
class SuperLongClassName(object):

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

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

你可能想要一个classmethod。它的工作方式与staticmethod类似,但将类作为隐式的第一个参数。

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