使用 self 与类名调用静态方法

DV8*_*2XL 12 python static-methods

使用类名调用 Python 静态方法更为常见,但对于长类名来说可能会让人眼花缭乱。有时我self在同一个类中使用调用静态方法,因为我发现它看起来更干净。

class ASomewhatLongButDescriptiveClassName:

   def __init__(self):
      # This works, but it's an eyesore
      ASomewhatLongButDescriptiveClassName.do_something_static()

      # This works too and looks cleaner.
      self.do_something_static()

   @staticmethod
   def do_something_static():
      print('Static method called.')
Run Code Online (Sandbox Code Playgroud)

我的理解是,调用静态方法self会被解释为ClassName.static_method(self),其中self静态方法将被忽略。
(编辑:上述陈述仅适用于实例方法,不适用于静态方法)

self我不应该在同一个类中调用静态方法有什么具体原因吗?

FWIW这是一个姊妹问题:Difference Between Calling Method with self and with class name? ,它处理非静态方法。

Gri*_*mar 28

您提出了一些不完全正确的说法:

使用类名调用 Python 静态方法更为常见

这并不常见,这是在课堂之外这样做的唯一方法。IE:

class MyClass:
    @staticmethod
    def a_method():
        pass


MyClass.a_method()
Run Code Online (Sandbox Code Playgroud)

在此示例中,self.a_method()将不起作用,因为self不会引用 的实例MyClass

使用 self 调用静态方法与 ClassName.static_method(self) 相同,其中 self 将被静态方法忽略

实际情况并非如此,例如:

class MyClass:
    @staticmethod
    def a_method():
        pass

    def another_method(self):
        # this is fine
        self.a_method()
        # this causes an error, as .a_method expects no arguments
        MyClass.a_method(self)
Run Code Online (Sandbox Code Playgroud)

self只是指调用实例方法的类的实例(它具有参数self,甚至不必调用self- 它只是调用第一个参数,self这是约定。

您可以在 上调用静态方法self,因为 self 是具有静态方法的类的实例,因此具有该方法。您还可以直接调用类上的静态方法,因为静态方法不需要对象实例作为第一个参数 - 这就是静态方法的要点。

您可以self.a_method()在您喜欢的地方使用,只需记住,self它将引用该对象实例化的类的对象,而不是您提到的特定类。

例如:

class ClassA:
    @staticmethod
    def a_method():
        print('a')

    def another_method(self):
        # prints whatever a_method for the class of self prints
        self.a_method()
        # always prints 'a', as a_method for ClassA prints 'a'
        ClassA.a_method()


class ClassB(ClassA):
    @staticmethod
    def a_method():
        print('b')


a = ClassA()
a.another_method()
b = ClassB()
b.another_method()
Run Code Online (Sandbox Code Playgroud)

输出:

class MyClass:
    @staticmethod
    def a_method():
        pass


MyClass.a_method()
Run Code Online (Sandbox Code Playgroud)

self.所以,你看,调用 from和 from之间是有区别的Class.