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

相关推荐
渡我白衣10 小时前
链接的迷雾:odr、弱符号与静态库的三国杀
android·java·开发语言·c++·人工智能·深度学习·神经网络
A.A呐10 小时前
【QT第三章】常用控件1
开发语言·c++·笔记·qt
Bony-10 小时前
Go语言并发编程完全指南-进阶版
开发语言·后端·golang
闲人编程10 小时前
将你的旧手机变成监控摄像头(Python + OpenCV)
python·opencv·智能手机·监控·codecapsule·oasis
007php00710 小时前
大厂深度面试相关文章:深入探讨底层原理与高性能优化
java·开发语言·git·python·面试·职场和发展·性能优化
SunnyDays101110 小时前
Python 复制和移动 Excel 工作表并保留所有格式:详解
python·复制excel工作表·移动excel工作表·重新排列excel工作表
say_fall10 小时前
C语言容易忽略的小知识点(1)
c语言·开发语言
不会编程的小寒10 小时前
C++初始继承,继承中构造、析构顺序
开发语言·python
运维管理11 小时前
Linux系统笔记--Base
开发语言·php
全栈软件开发11 小时前
最新版T5友价互站网源码商城PHP源码交易平台 完整带手机版源码网系统源码
android·开发语言·php