使用self与class名称调用静态方法

2024-09-28 16:58:33 发布

您现在位置:Python中文网/ 问答频道 /正文

使用类名调用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.')

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

我不应该使用self调用同一类中的静态方法,有什么具体原因吗

FWIW This is a sister question to Difference between calling method with self and with class name?, which deals with non-static methods.


Tags: andselfdefwithstaticthis事情do
1条回答
网友
1楼 · 发布于 2024-09-28 16:58:33

你做了一些不完全正确的陈述:

Calling Python static methods using the class name is more common

这并不常见,这是在课外进行的唯一方法。i、 e:

class MyClass:
    @staticmethod
    def a_method():
        pass


MyClass.a_method()

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

calling a static method with self is the same as ClassName.static_method(self), where self would be ignored by the static method

事实并非如此,例如:

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)

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()

输出:

a
a
b
a

因此,您可以看到,从self.调用和从Class.调用是有区别的

相关问题 更多 >