Python静态方法 - 如何从另一个方法调用方法

Pab*_*blo 76 python static-methods

当我有一个常规方法来调用类中的另一个方法时,我必须这样做

class test:
    def __init__(self):
        pass
    def dosomething(self):
        print "do something"
        self.dosomethingelse()
    def dosomethingelse(self):
        print "do something else"
Run Code Online (Sandbox Code Playgroud)

但是当我有静态方法时,我无法写

self.dosomethingelse()
Run Code Online (Sandbox Code Playgroud)

因为没有实例.我如何在Python中从同一个类的另一个静态方法调用静态方法?

编辑:多么糟糕.好的,我把问题编辑回原来的问题.我已经得到了Peter Hansen评论中第二个问题的答案.如果你认为我应该为我已经拥有的答案打开另一个问题,请告诉我.

war*_*iuc 108

我如何在Python中从同一个类的另一个静态方法调用静态方法?

class Test() :
    @staticmethod
    def static_method_to_call()
        pass

    @staticmethod
    def another_static_method() :
        Test.static_method_to_call()

    @classmethod
    def another_class_method(cls) :
        cls.static_method_to_call()
Run Code Online (Sandbox Code Playgroud)


jld*_*ont 69

class.method 应该管用.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()
Run Code Online (Sandbox Code Playgroud)

  • 这里应该添加建议:很明显,classmethods与staticmethods相比没有任何缺点,classmethods允许在将来扩展方法以调用其他类方法.因此,即使没有迫切需要,也应始终优先考虑. (14认同)

Emi*_*tai 12

如果被调用的函数与调用者静态方法位于同一类中,则可以调用__class__.dosomethingelse()而不是。self.dosomethingelse()

class WithStaticMethods:
    @staticmethod
    def static1():
        print("This is first static")

    @staticmethod
    def static2():
        # WithStaticMethods.static1()
        __class__.static1()
        print("This is static too")


WithStaticMethods.static2()
Run Code Online (Sandbox Code Playgroud)

印刷:

This is first static
This is static too
Run Code Online (Sandbox Code Playgroud)

  • 这应该被标记为正确答案。对我有用,谢谢。 (2认同)

Jas*_*ker 9

注意 - 看起来问题已经改变了一些.关于如何从静态方法调用实例方法的问题的答案是,如果不将实例作为参数传递或在静态方法中实例化该实例,则不能这样做.

以下内容主要是回答"如何从另一个静态方法调用静态方法":

请记住,有在Python静态方法和类方法之间的差异.静态方法不使用隐式的第一个参数,而类方法将类作为隐式的第一个参数(通常cls按惯例).考虑到这一点,以下是您将如何做到这一点:

如果它是静态方法:

test.dosomethingelse()
Run Code Online (Sandbox Code Playgroud)

如果是类方法:

cls.dosomethingelse()
Run Code Online (Sandbox Code Playgroud)

  • 更准确地说,您只能在类方法本身中使用 `cls.dosomethingelse()`。就像您只能在实例方法本身中使用 `self` 一样。 (3认同)

Ahm*_*aik 5

好的,类方法和静态方法之间的主要区别是:

  • 类方法具有自己的标识,这就是为什么必须在INSTANCE中调用它们的原因。
  • 另一方面,可以在多个实例之间共享静态方法,因此必须从CLASS中调用它

  • 这看起来不对——但是这里的意思很模糊,没有例子,所以很难说。主要是,“类方法”不必“从实例内”调用...您可以从了解“MyClass”的任何地方调用“MyClass.class_method()”(也许您正在考虑“实例方法”) ?) (2认同)