我有一个类,它返回机器的运行状况统计信息。Python - staticmethod vs classmethod
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_stats
将从课外被调用。这是定义相关功能的正确方法。使用classmethods
或staticmethods
或创建该类的对象,然后调用get_stats
。
我已经读了足够的差异,但仍然想通过一个例子来理解我的理解。哪种方法更为pythonic?
诚实的问题:你为什么要使用一个类?你似乎没有期望永远实例化它。我没有看到任何状态。为什么不只是一系列功能? – glibdud
'@ classmethod'和'@ staticmethod'是为了不同的事情。它们不可互换。当你想用一个类对一个函数进行逻辑分组时,应该使用'@ staticmethod',但该函数不需要状态。你可以把'@ classmethod'看作其他语言的重载构造函数。 –
@glibdud - 我更喜欢在特定的类中对特定域的功能进行分组。 – PythonEnthusiast