在静态方法中引用自己的类

时间:2013-07-11 22:04:45

标签: python

是否有在静态方法中引用自己的类的简写?

说我有这段代码:

class SuperLongClassName(object):

    @staticmethod
    def sayHi():
        print 'Hi'

    @staticmethod
    def speak():
        SuperLongClassName.sayHi()  # Is there a shorthand?

2 个答案:

答案 0 :(得分:9)

是的,请使用@classmethod代替@staticmethod@staticmethod的重点是删除额外的类参数,如果你不需要它。

class SuperLongClassName(object):

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

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

答案 1 :(得分:5)

您可能需要classmethod。它的作用类似于staticmethod,但将该类作为隐式的第一个参数。

class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(object):
    @classmethod
    def foo(cls):
         print cls.__name__

Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Claaa...

警告:

class Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass(
        Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass):
    pass

Subclaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass.foo() # prints Subclaaa...

或者,在模块级别为您的类定义一个较短的别名:

class Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2(object):
    @staticmethod
    def foo():
        return _cls2
_cls2 = Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2

# prints True
print (Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2 is
       Claaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaass2.foo())