3

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

假设我有这段代码:

class SuperLongClassName(object):

    @staticmethod
    def sayHi():
        print 'Hi'

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

2 回答 2

10

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

class SuperLongClassName(object):

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

    @classmethod
    def speak(cls):
        cls.sayHi()
于 2013-07-11T22:10:45.057 回答
5

你可能想要一个classmethod. 它像 a 一样工作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())
于 2013-07-11T22:09:08.217 回答