Python从类中引用类

时间:2013-11-22 22:31:44

标签: python class static-methods

我已经意识到@staticmethod - 下一个问题,您是否应该使用类名从类中引用这些方法?

class C:
    @staticmethod
    def imstatic():
        print("i'm static")

    @staticmethod
    def anotherstatic():
        # Is this the proper python way?
        C.imstatic()

    @staticmethod
    def brokenstatic():
        # This doesn't work..
        self.imstatic()

3 个答案:

答案 0 :(得分:1)

是的,因为您在静态方法中没有对该类的任何其他引用。您可以使用classmethod decorator

来制作这些类方法
class C:
    @staticmethod
    def imstatic():
        print("i'm static")

    @classmethod
    def anotherstatic(cls):
        cls.imstatic()

类方法 引用该类。

答案 1 :(得分:1)

如果您需要在静态方法中引用该类,您可能应该使用classmethod代替:

class C:
    @staticmethod
    def imstatic():
        print("i'm static")

    @classmethod
    def imclass(cls):
        cls.imstatic()

与实例方法“神奇地”给出对实例的引用作为第一个参数的方式相同,类方法被赋予对类的引用。您可以直接从实例或类中调用它们,例如以下两个都是有效的并且具有相同的行为:

C().imclass()
C.imclass()

话虽如此,如果您仍然想要使用静态方法,那么您当前的方法是正确的,只需按名称引用该类。

答案 2 :(得分:1)

如果您总是想要调用该特定类的静态方法,是的,您必须按名称指定它。如果你想支持覆盖静态方法,你想要的是一个类方法:它传递,在该方法上调用方法作为第一个参数,类似于常规上的self实例方法,因此您可以调用重写方法。一般来说,我建议使用classmethods。