python - 使静态方法显式引用该类

标签 python coding-style static-methods

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/

相关文章:

c# - 派生类在自己的静态方法中调用基类的静态方法

python - 从另一个文件导入类时出现问题

python - 用python找到不完整圆的交点

python - 编译 .pyx 文件时缺少 numpy/arrayobject.h

c++ - 我必须将数据设为私有(private)吗?

java - 在 Java 中格式化长方法调用的可接受方法是什么?

java - 如何摆脱 Android 中的口是心非?

python - 导入外部包的正确约定是什么?

java - 无法从静态方法调用 AsyncTask?

c++ - 从静态派生的基类实现虚方法