python:类中静态方法,类方法和实例方法的使用与区别

python 类里面常用的方法有3个:静态方法(@staticmethod),类方法(@classmethod)和实例方法(self)

1. 函数和方法

1.1 函数:

函数定义是由def()关键字定义

python 复制代码
def fun():
    a = "hello"
    return a

# 函数调用
res = fun()
print(res)

1.2 方法-实例方法(self)

定义在类中,同样也是由def()定义,但此时不再是函数,而是一种实例化方法

定义的方法默认在括号里面加一个self参数,self 是类本身的实例对象。

在调用的时候,需要先进行实例化

python 复制代码
class A(object):
    count = 0

    def fun(self):
        b = "world"
        return b

# A类不能直接调用fun
# print(A.fun())
a = A()
print(a.fun())

2. 静态方法(@staticmethod),类方法(@classmethod)

@staticmethod和@classmethod,就可以不需要实例化,直接类名.方法名()调用。

  • 静态方法对类一无所知,只处理参数
  • 类方法适用于类,因为它的参数始终是类本身。
  • 类方法可以由类及其对象调用。

2.1 静态方法

@staticmethod用于修饰类中的方法,使其可以再不创建类实例的情况下调用方法,这样做的好处是执行效率较高,当然也可像一般方法一样用实例调用该方法。

使用静态方法的好处是,可以在不创建类实例的情况下调用该方法,从而提高代码的灵活性和可重用性。

  • 静态方法可以不带任何参数,由于静态方法没有self参数,所以它无法访问类的实例成员
  • 静态方法也没有cls参数,所以它也无法访问类成员。静态方法既可以通过对象名调用,也可以通过类名调用。
python 复制代码
class A(object):
    count = 0

    def fun(self):
        b = "world"
        return b

    @staticmethod
    def start():
        print("start-----")

# 不用实例化也能调用
A.start()
# 实例化也能调用
a = A()
a.start()

2.2 类方法

  • 类方法是绑定到类而不是其对象的方法。
  • class方法始终附加到一个类,其中第一个参数作为类本身。
  • 不需要实例化,类名称直接调用类方法;实例化也能调用类方法

例1:

python 复制代码
class Person:
    age = 25
    def printAge(cls):
        print('The age is:', cls.age)
        
Person.printAge = classmethod(Person.printAge)
Person.printAge()

例2:

python 复制代码
class Person:
    age = 25
    @classmethod
    def printAge(cls):
        print('The age is:', cls.age)

Person.printAge()

例1和例2:输出一样!!

所以:@classmethod等价于Person.printAge = classmethod(Person.printAge)

@classmethod不需要self参数,但第一个参数需要是表示自身类的cls参数。

以下这个例子很好:

python 复制代码
class DataTest(object):
    day = 0
    month = 0
    year = 0

    def __init__(self, year=0, month=0, day=0):
        self.day = day
        self.month = month
        self.year = year

    def out_date(self):
        print("year :", self.year)
        print("month :", self.month)
        print("day :", self.day)

t = DataTest(2021, 8, 18)
t.out_date()

输出:

python 复制代码
year :2021
month :8
day :18

但是如果用户输入的是 "2016-8-1" 这样的字符格式,那么就需要调用Date_test 类前做一下处理:

python 复制代码
def get_data(cls, string_date):
   """处理'2018-8-18'字符格式"""
   year, month, day = map(int, string_date.split('-'))
   return cls(year, month, day)

string_date = '2018-8-18'
year, month, day = map(int, string_date.split('-'))
s = DataTest(year, month, day)
print(s.out_date())

那可不可以把这个字符串处理的函数放到 DateTest 类当中呢?

@classmethod :【类最基本的作用是实例化出一个对象,但是有的时候再实例化之前,就需要先和类做一定的交互,这种交互可能会影响实际实例化的过程,所以必须放在调用构造函数之前。】

python 复制代码
class DataTest(object):
    day = 0
    month = 0
    year = 0

    def __init__(self, year=0, month=0, day=0):
        self.day = day
        self.month = month
        self.year = year

    def out_date(self):
        print("year :", self.year)
        print("month :", self.month)
        print("day :", self.day)

    @classmethod
    def get_data(cls, string_date):
        """处理'2018-8-18'字符格式"""
        year, month, day = map(int, string_date.split('-'))
        return cls(year, month, day)

定义一个get_data类方法,处理完字符串后返回这个类的实例对象。这样有一举两得的效果,在处理字符串的同时,还能实现实例化。

python 复制代码
r = DataTest.get_data('2018-8-18') 
r.out_date()

参考:
https://zhuanlan.zhihu.com/p/544021480
https://blog.csdn.net/qq_46906413/article/details/124332735

相关推荐
liulilittle12 分钟前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师19 分钟前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
Tipriest_20 分钟前
Python关键字梳理
python·关键字·keyword
勤奋的知更鸟25 分钟前
Java 编程之模板方法模式
java·开发语言·模板方法模式
上单带刀不带妹1 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
im_AMBER2 小时前
学习日志05 python
python·学习
大虫小呓2 小时前
Python 处理 Excel 数据 pandas 和 openpyxl 哪家强?
python·pandas
哪 吒2 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
-凌凌漆-2 小时前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼2 小时前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin