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

MyClass.the_static_method()

当前回答

Python中的静态方法?是否可以在Python中使用静态方法,以便我可以调用它们而不初始化类,例如:ClassName.StaticMethod()

是的,静态方法可以这样创建(虽然使用下划线而不是CamelCase来创建方法有点像Python):

class ClassName(object):

    @staticmethod
    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

上面使用了decorator语法。此语法等效于

class ClassName(object):

    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

    static_method = staticmethod(static_method)

这可以按照您所描述的方式使用:

ClassName.static_method()

静态方法的一个内置示例是Python 3中的str.maketrans(),它是Python 2中字符串模块中的一个函数。


正如您所描述的,另一个可以使用的选项是classmethod,不同之处在于classmethod将类作为隐式第一个参数,如果是子类,则将子类作为隐的第一个参数。

class ClassName(object):

    @classmethod
    def class_method(cls, kwarg1=None):
        '''return a value that is a function of the class and kwarg1'''

请注意,cls不是第一个参数的必需名称,但如果您使用其他名称,大多数有经验的Python程序员会认为它做得很糟糕。

这些通常用作替代构造函数。

new_instance = ClassName.class_method()

内置示例是dict.fromkeys():

new_dict = dict.fromkeys(['key1', 'key2'])

其他回答

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

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

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

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

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

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

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

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

Python中的静态方法?是否可以在Python中使用静态方法,以便我可以调用它们而不初始化类,例如:ClassName.StaticMethod()

是的,静态方法可以这样创建(虽然使用下划线而不是CamelCase来创建方法有点像Python):

class ClassName(object):

    @staticmethod
    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

上面使用了decorator语法。此语法等效于

class ClassName(object):

    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

    static_method = staticmethod(static_method)

这可以按照您所描述的方式使用:

ClassName.static_method()

静态方法的一个内置示例是Python 3中的str.maketrans(),它是Python 2中字符串模块中的一个函数。


正如您所描述的,另一个可以使用的选项是classmethod,不同之处在于classmethod将类作为隐式第一个参数,如果是子类,则将子类作为隐的第一个参数。

class ClassName(object):

    @classmethod
    def class_method(cls, kwarg1=None):
        '''return a value that is a function of the class and kwarg1'''

请注意,cls不是第一个参数的必需名称,但如果您使用其他名称,大多数有经验的Python程序员会认为它做得很糟糕。

这些通常用作替代构造函数。

new_instance = ClassName.class_method()

内置示例是dict.fromkeys():

new_dict = dict.fromkeys(['key1', 'key2'])

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

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