禁用 class 实例化的最佳实践

best practice to disable a class instanciating

我想创建一个只包含静态成员的 utils-class,例如

class A(object):
  X = 0
  @staticmethod
  def f():
    print X

我还希望在没有实例的情况下使用所有方法,即我希望用户调用 A.f() 而不是 a = A(); a.f()

一种方法是使用 @abc.abstractmethod,例如

class A(object):
  X = 0
  @abc.abstractmethod
  def __init__(self):
    raise Exception('Should not be created!')
  @staticmethod
  def f():
    print X

第二个选项不使用抽象,因为它意味着继承,这不是我在此 class 设计的东西。在这种情况下,我只会从 __init____new__

中提出异常

最佳做法是什么(第三种选择?)

pythonic 方式是将所有这些静态函数放在一个模块中。这些函数之间没有共享状态,为什么必须使用 class?

鉴于您问的是 "best practice" 是什么,而不是技术上如何做到这一点,我可以回答您,最好的做法是不要那样做 ;) 我以前从未见过这样的结构,我相信它违反了两个 Python "principles":

  • 我们都是成年人。
  • 最小惊讶原则。

我们都是成年人

This expression is also used in the object-oriented python literature to explain python's attitudes about private class members, which Python doesn't have.

When you create an instance of some class there is nothing to prevent you from poking around inside and using various internal, private methods that are (a) necessary for the class to function, BUT (b) not intended for direct use/access.

After all, we're all consenting adults here.

来自:https://mail.python.org/pipermail/tutor/2003-October/025932.html

最小惊讶原则。

The principle of least astonishment applies to user interface and software design. A typical formulation of the principle, from 1984, is: "If a necessary feature has a high astonishment factor, it may be necessary to redesign the feature."

More generally, the principle means that a component of a system should behave in a way that most users will expect it to behave; the behavior should not astonish or surprise users.

来自:https://en.wikipedia.org/wiki/Principle_of_least_astonishment