Static methods in Python?

后端 未结 10 936
悲&欢浪女
悲&欢浪女 2020-11-22 02:36

Is it possible to have static methods in Python which I could call without initializing a class, like:

ClassName.static_method()
10条回答
  •  Happy的楠姐
    2020-11-22 02:55

    I encounter this question from time to time. The use case and example that I am fond of is:

    jeffs@jeffs-desktop:/home/jeffs  $ python36
    Python 3.6.1 (default, Sep  7 2017, 16:36:03) 
    [GCC 6.3.0 20170406] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import cmath
    >>> print(cmath.sqrt(-4))
    2j
    >>>
    >>> dir(cmath)
    ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
    >>> 
    

    It does not make sense to create an object of class cmath, because there is no state in a cmath object. However, cmath is a collection of methods that are all related in some way. In my example above, all of the functions in cmath act on complex numbers in some way.

提交回复
热议问题