Python-staticmethod与classmethod

Python-staticmethod与classmethod,python,Python,我有一个类,它返回机器的运行状况统计信息 class HealthMonitor(object): """Various HealthMonitor methods.""" @classmethod def get_uptime(cls): """Get the uptime of the system.""" return uptime() @classmethod def detect_platform(cls):

我有一个类,它返回机器的运行状况统计信息

class HealthMonitor(object):
    """Various HealthMonitor methods."""

    @classmethod
    def get_uptime(cls):
        """Get the uptime of the system."""
        return uptime()

    @classmethod
    def detect_platform(cls):
        """Platform detection."""
        return platform.system()

    @classmethod
    def get_cpu_usage(cls):
        """Return CPU percentage of each core."""
        return psutil.cpu_percent(interval=1, percpu=True)

    @classmethod
    def get_memory_usage(cls):
        """Return current memory usage of a machine."""
        memory = psutil.virtual_memory()
        return {
            'used': memory.used,
            'total': memory.total,
            'available': memory.available,
            'free': memory.free,
            'percentage': memory.percentage
        }

    @classmethod
    def get_stats(cls):
        return {
            'memory_usage': cls.get_memory_usage(),
            'uptime': cls.uptime(),
            'cpu_usage': cls.get_cpu_usage(),
            'security_logs': cls.get_windows_security_logs()
        }
方法
get\u stats
将从类外部调用。这是定义相关函数的正确方法。使用
classmethods
staticmethods
或创建类的对象,然后调用
get\u stats


关于这些差异,我已经读得够多了,但仍然想用一个例子来澄清我的理解。哪一种方法更像python?

好吧,
类基本上提供了对数据的封装,即对特定数据的一组行为,用于标识该对象。现在,您定义的所有方法都与该类没有任何关系

因此,只要您不需要在这些方法之间共享数据,使用
classmethods
就毫无意义。尽管您最好使用
静态方法
,但它们所能做的只是提供一个名称空间。在名为
health\u monitor.py
的文件中将所有方法定义为简单函数,然后按如下方式使用,怎么样-

import health_monitor

uptime = health_monitor.get_uptime()

这种方法的唯一缺点是,您必须强制执行按模块名称而不是函数导入的约定。

当方法需要类信息时,即访问类属性时,请使用
@classmethod
。(假设health_monitor类具有OS属性,这将影响您执行的命令)

当方法不需要声明它的类的任何数据时,使用
@staticmethod
;喜欢你所有的功能

为了简单起见,我经常使用
staticmethod
处理我放在类中的函数,因为它们是在我的类的上下文中运行的,而不是依赖它

<>您的<强>类< /强>:当您的所有方法都是“代码>类方法< /COD>或<代码> STATIC方法时,您应该考虑将代码驻留在<强>模块<强>范围内,而不是一个类。为什么?嗯,如果它们之间不共享任何数据,就没有理由将它们分组到一个类中。这将更加简单:

# health_monitor.py
def get_uptime(cls):
    """Get the uptime of the system."""
    return uptime()

# main.py
health_monitor.get_uptime()

诚实的问题:你为什么要使用一个类?您似乎并不期望将其实例化。我看不到任何状态。为什么不只是一组函数呢?
@classmethod
@staticmethod
用于不同的用途。它们不能互换
@staticmethod
当您希望将函数与类进行逻辑分组,但该函数不需要状态时,应使用。您可以将
@classmethod
视为其他语言中的重载构造函数。@pythonthus您要求的最“pythonic方法”是将这些函数分组到一个模块中,而不是将它们放入一个从未实例化过的类中。@E.Ducateme,正如Bilkokuya提到的,模块也可以,根据我的经验,这是Python中更常见的方法。这个问答提供了一些合理的说明,说明何时何地使用classmethods和staticmethods: