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

MyClass.the_static_method()

当前回答

您可以使用@staticmethoddecorator定义静态方法,如下所示。我在Python中对@classmethod vs@staticmethod的回答中详细解释了@staticmmethod decorator和@classmethoddecorator,并在Python中什么是“实例方法”的回答中解释了实例方法:

class Person:
    @staticmethod # Here
    def test():
        print("Test")

其他回答

是的,使用静态方法装饰器:

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

注意,一些代码可能使用旧的定义静态方法的方法,使用staticmethod作为函数而不是修饰符。仅当您必须支持Python的早期版本(2.2和2.3)时,才应使用此选项:

class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

这与第一个示例(使用@staticmethod)完全相同,只是没有使用漂亮的decorator语法。

最后,谨慎使用静态方法!在Python中很少有静态方法是必需的,而且我已经多次看到它们被使用,而单独的“顶级”函数会更清晰。


以下是文件中的逐字内容:

静态方法不接收隐式第一个参数。要声明静态方法,请使用以下习惯用法:C类:@静态方法定义f(arg1,arg2,…):。。。@staticmethod表单是一个函数装饰器–有关详细信息,请参阅函数定义中的函数定义描述。它既可以在类(如C.f())上调用,也可以在实例(如C().f())中调用。除了它的类之外,该实例将被忽略。Python中的静态方法与Java或C++中的方法类似。有关更高级的概念,请参阅classmethod()。有关静态方法的更多信息,请参阅标准类型层次结构中有关标准类型层次的文档。2.2版中的新增功能。在版本2.4中进行了更改:添加了函数修饰符语法。

是的,请查看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中的所有函数都以某种方式作用于复数。

总结其他人的回答并补充,在python中声明静态方法或变量有很多种方法。

使用staticmethod()作为装饰符:可以简单地在声明的方法(函数)上方放置一个修饰符,使其成为静态方法。例如。

class Calculator:
    @staticmethod
    def multiply(n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 * n2 * Res

print(Calculator.multiply(1, 2, 3, 4))              # 24

使用staticmethod()作为参数函数:此方法可以接收函数类型的参数,并返回传递函数的静态版本。例如。

class Calculator:
    def add(n1, n2, *args):
        return n1 + n2 + sum(args)

Calculator.add = staticmethod(Calculator.add)
print(Calculator.add(1, 2, 3, 4))                   # 10

使用classmethod()作为装饰符:@classmethod对函数的影响与@staticmethod类似,但是这一次,需要在函数中接受一个额外的参数(类似于实例变量的self参数)。例如。

class Calculator:
    num = 0
    def __init__(self, digits) -> None:
        Calculator.num = int(''.join(digits))

    @classmethod
    def get_digits(cls, num):
        digits = list(str(num))
        calc = cls(digits)
        return calc.num

print(Calculator.get_digits(314159))                # 314159

使用classmethod()作为参数函数:@classmethod也可以用作参数函数,以防不想修改类定义。例如。

class Calculator:
    def divide(cls, n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 / n2 / Res

Calculator.divide = classmethod(Calculator.divide)

print(Calculator.divide(15, 3, 5))                  # 1.0

直接申报在所有其他方法外部但在类内部声明的方法/变量自动是静态的。

class Calculator:   
    def subtract(n1, n2, *args):
        return n1 - n2 - sum(args)

print(Calculator.subtract(10, 2, 3, 4))             # 1

整个计划

class Calculator:
    num = 0
    def __init__(self, digits) -> None:
        Calculator.num = int(''.join(digits))
    
    
    @staticmethod
    def multiply(n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 * n2 * Res


    def add(n1, n2, *args):
        return n1 + n2 + sum(args)
    

    @classmethod
    def get_digits(cls, num):
        digits = list(str(num))
        calc = cls(digits)
        return calc.num


    def divide(cls, n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 / n2 / Res


    def subtract(n1, n2, *args):
        return n1 - n2 - sum(args)
    



Calculator.add = staticmethod(Calculator.add)
Calculator.divide = classmethod(Calculator.divide)

print(Calculator.multiply(1, 2, 3, 4))              # 24
print(Calculator.add(1, 2, 3, 4))                   # 10
print(Calculator.get_digits(314159))                # 314159
print(Calculator.divide(15, 3, 5))                  # 1.0
print(Calculator.subtract(10, 2, 3, 4))             # 1

有关掌握Python中的OOP,请参阅Python文档。

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

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。