使静态方法显式引用类



Python 不仅允许从类调用静态方法,还可以从实例调用静态方法:

class X:
  @staticmethod
  def f():
    print('f')
x = X()
X.f() 
x.f() # same as above

当我们只有一个实例可以使用时,这可能很方便;毕竟,谁想写x.__class__.f()而不是x.f()

但我发现许多代码的读者(包括我自己)倾向于将x.f()解释为实例方法。也就是说,他们假设所做的任何事情要么使用要么改变x。在某些情况下,这甚至会导致错误(开发人员错误地解释了f的语义)。

所以我在考虑采用一种约定,其中所有静态方法仅使用类对象调用。是否有任何静态分析工具会在违反此约定时警告我?

我不

认为这种静态检查是pythonic的,但是...

class enforced_staticmethod(staticmethod):
     def __get__(self, instance, cls):
         if instance is not None:
             raise Exception('Do not call with an instance.')
         return super(enforced_staticmethod, self).__get__(self)

class C:
    @enforced_staticmethod
    def hai(x):
        return x + 1

您可以测试:

>>> C.hai(10)
11
>>> C().hai(10)
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    C().hai(10)
  File "<pyshell#48>", line 4, in __get__
    raise Exception('Do not call with an instance.')
Exception: Do not call with an instance.

最新更新