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
的语义)。
所以我正在考虑采用一种约定,即仅使用类对象调用所有静态方法。如果违反此约定,是否有任何静态分析工具会警告我?
最佳答案
我不认为这么多的静态检查是Python式的,但是......
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.
关于python - 使静态方法显式引用该类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12850828/