【问题标题】:calling static method from inside the class [closed]从类内部调用静态方法[关闭]
【发布时间】:2015-01-22 22:47:30
【问题描述】:

从类(包含静态方法)内部调用静态方法时,可以通过以下方式完成:
Class.method() 或 self.method()
有什么不同?
每个都有哪些独特的用例?

class TestStatic(object):
    @staticmethod
    def do_something():
        print 'I am static'

    def use_me(self):
        self.do_something() # 1st way
        TestStatic.do_something() # 2nd way

t = TestStatic()
t.use_me()

打印

I am static
I am static

【问题讨论】:

  • 自我更好。它适用于继承,或者如果您重命名类。
  • 为了可读性,我更喜欢 class.method。

标签: python static-methods


【解决方案1】:

通过使用TestStatic.do_something(),您可以绕过子类的任何覆盖:

class SubclassStatic(TestStatic):
    @staticmethod
    def do_something():
        print 'I am the subclass'

s = SubclassStatic()
s.use_me()

将打印

I am the subclass
I am static

这可能是您想要的,也可能不是。选择最符合您期望的方法。

【讨论】:

    【解决方案2】:

    我相信TestStatic.do_something() 更好,因为它展示了对静态成员的理解。静态成员是属于该类的对象和在该类上调用的方法,并且在大多数情况下,它们是实用程序类。因此,通过类调用方法更为合适。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多