【Python面向对象编程】第10篇 静态方法

本篇我们介绍 Python 静态方法(static method)的概念,以及如何利用静态方法创建工具类。

静态方法简介

目前,我们已经学习了实例方法和类方法。实例方法和具体实例相关联,可以访问和修改相关对象的状态。类方法和类相关联,可以访问和修改类的状态。

静态方法和实例方法的不同之处在于它们不属于具体的对象,因此无法访问和修改对象的状态。同时,Python 不会隐式将 cls 参数或者 self 参数传递给静态方法。所以静态方法也不能访问和修改类的状态。

在实际使用中,我们通常使用静态方法定义一些实用方法,或者将逻辑相关的函数组合成一个工具类。

静态方法使用 @staticmethod 装饰器进行定义:

class className:
    @staticmethod
    def static_method_name(param_list):
        pass

调用静态方法的语法如下:

className.static_method_name()

静态方法和类方法

静态方法和类方法非常类似,但是它们之间存在明显的区别。下表列出了它们之间的区别:

类方法静态方法
Python 隐式将 cls 参数传递给类方法。Python 不会隐式将 cls 参数传递给静态方法。
类方法可以访问和修改类的状态。静态方法不能访问和修改类的状态。
使用 @classmethod 装饰器定义类方法。使用 @staticmethod 装饰器定义静态方法。

静态方法示例

以下示例定义了一个 TemperatureConverter 类,其中的几个静态方法用于摄氏温度、华氏温度以及开氏温度之间的转换:

class TemperatureConverter:
    KEVIN = 'K',
    FAHRENHEIT = 'F'
    CELSIUS = 'C'

    @staticmethod
    def celsius_to_fahrenheit(c):
        return 9*c/5 + 32

    @staticmethod
    def fahrenheit_to_celsius(f):
        return 5*(f-32)/9

    @staticmethod
    def celsius_to_kelvin(c):
        return c + 273.15

    @staticmethod
    def kelvin_to_celsius(k):
        return k - 273.15

    @staticmethod
    def fahrenheit_to_kelvin(f):
        return 5*(f+459.67)/9

    @staticmethod
    def kelvin_to_fahrenheit(k):
        return 9*k/5 - 459.67

    @staticmethod
    def format(value, unit):
        symbol = ''
        if unit == TemperatureConverter.FAHRENHEIT:
            symbol = '°F'
        elif unit == TemperatureConverter.CELSIUS:
            symbol = '°C'
        elif unit == TemperatureConverter.KEVIN:
            symbol = '°K'

        return f'{value}{symbol}'

以下代码调用了 TemperatureConverter 类静态方法:

f = TemperatureConverter.celsius_to_fahrenheit(35)
print(TemperatureConverter.format(f, TemperatureConverter.FAHRENHEIT))

总结

  • 使用静态方法定义一些实用方法,或者将逻辑相关的函数组合成一个工具类。
  • 使用 @staticmethod 装饰器定义静态方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不剪发的Tony老师

为 5 个 C 币而折腰。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值