我可以定义一个可以直接在类实例上调用的静态方法吗?例如。,

MyClass.the_static_method()

当前回答

我不时遇到这个问题。我喜欢的用例和示例是:

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']
>>> 

创建cmath类的对象是没有意义的,因为cmath对象中没有状态。然而,cmath是一组方法的集合,它们都以某种方式相关。在我上面的例子中,cmath中的所有函数都以某种方式作用于复数。

其他回答

您实际上不需要使用@staticmethoddecorator。只需声明一个方法(不需要self参数)并从类中调用它。装饰器仅在您希望能够从实例调用它时才存在(这不是您想要做的)

大多数情况下,你只是使用函数。。。

也许最简单的选择就是将这些函数放在类之外:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def bark(self):
        if self.name == "Doggy":
            return barking_sound()
        else:
            return "yip yip"

def barking_sound():
    return "woof woof"

使用此方法,可以将修改或使用内部对象状态(具有副作用)的函数保留在类中,并且可以将可重用的实用程序函数移到外部。

假设这个文件名为dogs.py。要使用这些文件,您可以调用dogs.barking_sound()而不是dogs.Dog.barking_sound。

如果确实需要静态方法作为类的一部分,可以使用staticmethoddecorator。

因此,静态方法是可以在不创建类对象的情况下调用的方法。例如:-

    @staticmethod
    def add(a, b):
        return a + b

b = A.add(12,12)
print b

在上面的示例中,add是由类名A而不是对象名调用的。

是的,请查看staticmethoddecorator:

>>> class C:
...     @staticmethod
...     def hello():
...             print "Hello World"
...
>>> C.hello()
Hello World

我不时遇到这个问题。我喜欢的用例和示例是:

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']
>>> 

创建cmath类的对象是没有意义的,因为cmath对象中没有状态。然而,cmath是一组方法的集合,它们都以某种方式相关。在我上面的例子中,cmath中的所有函数都以某种方式作用于复数。