百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

python静态方法和类方法之内置函数

off999 2024-09-20 22:49 22 浏览 0 评论

python类方法分为实例方法、类方法、静态方法。

(1) 实例方法,不用修饰,第1个参数为实例对象,默认为self。

通过实例调用时,自动将当前实例传给self;

通过类调用时,需要显式将实例传给self。

(2) 类方法,用@classmethod修饰,第1个参数为类对象,默认为cls。

也可以通过内置函数classmethod(cmeth)将cmeth转为类方法。

通过实例调用时,自动将当前类传递给第1个参数;

通过类调用时,自动将当前类传递给第1个参数。

(3) 静态方法,用@staticmethod修饰,第1个参数不需要默认,无self和cls。

也可以通过内置函数staticmethod(smeth)将smeth转为静态方法。

通过实例调用时,不会自动将当前实例传给第1个参数。

通过类调用时,不需要传送实例给第1个参数。


python2.2版本新增类方法和静态方法,对经典类有效,对新式类无效。


1.1 python类方法

python类方法通过@classmethod修饰,或通过内置函数classmethod()转换。类方法第1个参数为类对象,默认为cls。通过实例调用时,自动将当前类传递给第1个参数,通过类调用时,自动将当前类传递给第1个参数。

类方法适合处理每个类中不同的数据,通过第1个入参cls完成。

1.2 python静态方法

python静态方法通过@staticmethod修饰,或通过内置函数staticmehod()转换。静态方法入参无self和cls。通过实例调用时,不会自动将当前实例传给第1个参数,通过类调用时,不需要显式传递实例给第1个参数。


python静态方法用于处理与类而不是与实例相关的数据。

比如,记录类创建的实例数。

把计数器作为类属性,每次创建实例对象时,构造函数对计数器加1.

类属性是所有实例共享的,可以被所有实例使用。

1.2.1 类内未使用静态方法的无参方法

描述

python2.x和3.x,类的方法未定义第1个入参,通过类和实例调用结果不同。

 class NoStaticMed:
     def printNumOfIns():
         pass


NO

调用方式

调用举例

python2.x

python3.x

1

类调用

NoStaticMed.printNumOfIns()

报错

成功

2

实例调用

NoStaticMed ().printNumOfIns()

报错

报错

示例

staticmedcls.py

 # coding:utf-8
 import sys
 print('python版本为:python{}'.format(sys.version.split(' ')[0]))
 class NoStaticMed:
     numOfInstances=0
     def __init__(self):
         NoStaticMed.numOfInstances+=1
     def printNumOfIns():
         print('创建的实例数为:{}'.format(NoStaticMed.numOfInstances))

python2.x在idle执行结果

 >>> import os
 >>> os.chdir(r'E:\documents\F盘')
 >>> from staticmedcls import NoStaticMed
 python版本为:python2.7.18
 >>> sm1=NoStaticMed()
 >>> sm2=NoStaticMed()
 >>> sm3=NoStaticMed()
 >>> NoStaticMed.printNumOfIns()
 # python 2.x 通过类调用无入参类方法,报 无绑定方法 必须传实例作为第1个入参。
 Traceback (most recent call last):
   File "<pyshell#6>", line 1, in <module>
     NoStaticMed.printNumOfIns()
 TypeError: unbound method printNumOfIns() must be called with NoStaticMed instance as first argument (got nothing instead)
 >>> sm1.printNumOfIns()
 # python 2.x 通过实例调用无入参类方法,报 收到1个入参。即会自动传入一个实例。
 Traceback (most recent call last):
   File "<pyshell#7>", line 1, in <module>
     sm1.printNumOfIns()
 TypeError: printNumOfIns() takes no arguments (1 given)

python3.x在idle执行结果

 >>> import os
 >>> os.chdir(r'E:\documents\F盘')
 >>> from staticmedcls import NoStaticMed
 python版本为:python3.7.8
 >>> sm1=NoStaticMed()
 >>> sm2=NoStaticMed()
 >>> sm3=NoStaticMed()
 # python 3.x 通过类调用无入参类方法,成功。
 >>> NoStaticMed.printNumOfIns()
 创建的实例数为:3
 >>> sm1.printNumOfIns()
 # python 3.x 通过实例调用无入参类方法,报 收到1个入参。即会自动传入一个实例。
 Traceback (most recent call last):
   File "<pyshell#7>", line 1, in <module>
     sm1.printNumOfIns()
 TypeError: printNumOfIns() takes 0 positional arguments but 1 was given

1.2.2 类外无参方法

描述

在类外定义一个函数,用于统计类创建的实例数量。

示例

 # coding:utf-8
 import sys
 print('python版本为:python{}'.format(sys.version.split(' ')[0]))
 class OutClassMed:
     numOfInstances=0
     def __init__(self):
         OutClassMed.numOfInstances+=1
 def printNumOfIns():
     print('从 OutClassMed 创建的实例数为:{}'.format(OutClassMed.numOfInstances))
 

python2.x在idle执行结果

 >>> import os;os.chdir(r'E:\documents\F盘')
 >>> from staticmedcls import OutClassMed,printNumOfIns
 python版本为:python2.7.18
 >>> ocm1,ocm2,ocm3=OutClassMed(),OutClassMed(),OutClassMed()
 >>> printNumOfIns()
 从 OutClassMed 创建的实例数为:3

python3.x在idle执行结果

 >>> import os;os.chdir(r'E:\documents\F盘')
 >>> from staticmedcls import OutClassMed,printNumOfIns
 python版本为:python3.7.8
 >>> ocm1=OutClassMed();ocm2=OutClassMed();ocm3=OutClassMed()
 >>> printNumOfIns()
 从 OutClassMed 创建的实例数为:3

1.2.3 内置函数staticmethod和classmethod

描述

使用内置函数staticmethod()转为静态方法,

使用内置函数classmethod()转为类方法。

示例

Python2.x在idle执行结果

 >>> import sys
 >>> print('python版本为:python{}'.format(sys.version.split(' ')[0]))
 python版本为:python2.7.15
 >>> class BuiltInSCMed:
     def instanceMed(self,x):
         print(self,x)
     def staticMed(x):
         print(x)
     def clsMed(cls,x):
         print(cls,x)
     # 通过内置函数 staticmethod 将 staticMed 转为静态方法
     staticMed=staticmethod(staticMed)
     # 通过内置函数 classmethod 将 clsMed 转为类方法
     staticMed=classmethod(clsMed)
 >>> biscm1=BuiltInSCMed()
 # 通过实例调用实例方法
 >>> biscm1.instanceMed(1)
 (<__main__.BuiltInSCMed instance at 0x03B71620>, 1)
 # 通过类调用实例方法
 >>> BuiltInSCMed.instanceMed(biscm1,2)
 (<__main__.BuiltInSCMed instance at 0x03B71620>, 2)
 # 通过类调用静态方法
 >>> BuiltInSCMed.staticMed(3)
 3
 # 通过实例调用静态方法
 >>> biscm1.staticMed('梯阅线条')
 梯阅线条
 # 通过类调用类方法
 >>> BuiltInSCMed.clsMed('tyxt.work')
 (<class __main__.BuiltInSCMed at 0x03CD6650>, 'tyxt.work')
 # 通过实例调用类方法
 >>> biscm1.clsMed('tyxt.work')
 (<class __main__.BuiltInSCMed at 0x03CD6650>, 'tyxt.work')

Python3.x在idle执行结果

 >>> import sys
 >>> print('python版本为:python{}'.format(sys.version.split(' ')[0]))
 python版本为:python3.9.0
 >>> class BuiltInSCMed:
     def instanceMed(self,x):
         print(self,x)
     def staticMed(x):
         print(x)
     def clsMed(cls,x):
         print(cls,x)
     staticMed=staticmethod(staticMed)
     clsMed=classmethod(clsMed)
 >>> biscm1=BuiltInSCMed()
 >>> biscm1.instanceMed(1)
 <__main__.BuiltInSCMed object at 0x000001B16B6FEBB0> 1
 >>> BuiltInSCMed.instanceMed(biscm1,2)
 <__main__.BuiltInSCMed object at 0x000001B16B6FEBB0> 2
 >>> BuiltInSCMed.staticMed(3)
 3
 >>> biscm1.staticMed('梯阅线条')
 梯阅线条
 >>> BuiltInSCMed.clsMed('tyxt.work')
 <class '__main__.BuiltInSCMed'> tyxt.work
 >>> biscm1.clsMed('tyxt.work')
 <class '__main__.BuiltInSCMed'> tyxt.work

1.2.4 内置函数staticmethod转换的静态方法统计实例

python2.x 和3.x 在idle 执行结果 相同

 >>> class CountInsBISM:
     numOfInstances=0
     def __init__(self):
         CountInsBISM.numOfInstances+=1
     def printNumOfIns():
         print('创建的实例数为:{}'.format(CountInsBISM.numOfInstances))
     printNumOfIns=staticmethod(printNumOfIns)
 >>> cibs1,cibs2,cibs3=CountInsBISM(),CountInsBISM(),CountInsBISM()
 >>> CountInsBISM.printNumOfIns()    # 通过类调用
 创建的实例数为:3
 >>> cibs1.printNumOfIns()   # 通过实例调用
 创建的实例数为:3

1.2.5 内置函数classmethod转换的类方法统计实例

python2.x 和3.x 在idle 执行结果 相同

 >>> class CountInsBICM:
     numOfInstances=0
     def __init__(self):
         CountInsBICM.numOfInstances+=1
     def printNumOfIns(cls):
         print('创建的实例数为:{}'.format(cls.numOfInstances))
     printNumOfIns=classmethod(printNumOfIns)
 
 >>> cibc1,cibc2,cibc3=CountInsBICM(),CountInsBICM(),CountInsBICM()
 >>> CountInsBICM.printNumOfIns()    # 通过类调用
 创建的实例数为:3
 >>> cibc1.printNumOfIns()   # 通过实例调用
 创建的实例数为:3

1.2.6 统计每个类的实例

通过类方法统计继承中每个类的实例。

需要在继承中,每个类各自维护一个实例数属性,用于存放各自数据。

示例

 >>> class CountInsEC:
     numOfInstances=0
     def countcls(cls):
         cls.numOfInstances+=1
     def __init__(self):
         self.countcls()
     countcls=classmethod(countcls)
 
     
 >>> class SubA(CountInsEC):
     numOfInstances=0
     def __init__(self):
         CountInsEC.__init__(self)
 
         
 >>> class SubB(CountInsEC):
     numOfInstances=0
 
     
 >>> ciec1,ciec2,ciec3=CountInsEC(),CountInsEC(),CountInsEC()
 >>> suba1,suba2=SubA(),SubA()
 >>> subb1=SubB()
 >>> ciec1.numOfInstances,suba1.numOfInstances,subb1.numOfInstances
 (3, 2, 1)
 >>> CountInsEC.numOfInstances,SubA.numOfInstances,SubB.numOfInstances
 (3, 2, 1)

本文首发微信公众号:梯阅线条

更多内容参考python知识分享或软件测试开发目录。

相关推荐

python入门到脱坑经典案例—清空列表

在Python中,清空列表是一个基础但重要的操作。clear()方法是最直接的方式,但还有其他方法也可以实现相同效果。以下是详细说明:1.使用clear()方法(Python3.3+推荐)...

python中元组,列表,字典,集合删除项目方式的归纳

九三,君子终日乾乾,夕惕若,厉无咎。在使用python过程中会经常遇到这四种集合数据类型,今天就对这四种集合数据类型中删除项目的操作做个总结性的归纳。列表(List)是一种有序和可更改的集合。允许重复...

Linux 下海量文件删除方法效率对比,最慢的竟然是 rm

Linux下海量文件删除方法效率对比,本次参赛选手一共6位,分别是:rm、find、findwithdelete、rsync、Python、Perl.首先建立50万个文件$testfor...

数据结构与算法——链式存储(链表)的插入及删除,

持续分享嵌入式技术,操作系统,算法,c语言/python等,欢迎小友关注支持上篇文章我们讲述了链表的基本概念及一些查找遍历的方法,本篇我们主要将一下链表的插入删除操作,以及采用堆栈方式如何创建链表。链...

Python自动化:openpyxl写入数据,插入删除行列等基础操作

importopenpyxlwb=openpyxl.load_workbook("example1.xlsx")sh=wb['Sheet1']写入数据#...

在Linux下软件的安装与卸载(linux里的程序的安装与卸载命令)

通过apt安装/协助软件apt是AdvancedPackagingTool,是Linux下的一款安装包管理工具可以在终端中方便的安装/卸载/更新软件包命令使用格式:安装软件:sudoapt...

Python 批量卸载关联包 pip-autoremove

pip工具在安装扩展包的时候会自动安装依赖的关联包,但是卸载时只删除单个包,无法卸载关联的包。pip-autoremove就是为了解决卸载关联包的问题。安装方法通过下面的命令安装:pipinsta...

用Python在Word文档中插入和删除文本框

在当今自动化办公需求日益增长的背景下,通过编程手段动态管理Word文档中的文本框元素已成为提升工作效率的关键技术路径。文本框作为文档排版中灵活的内容容器,既能承载多模态信息(如文字、图像),又可实现独...

Python 从列表中删除值的多种实用方法详解

#Python从列表中删除值的多种实用方法详解在Python编程中,列表(List)是一种常用的数据结构,具有动态可变的特性。当我们需要从列表中删除元素时,根据不同的场景(如按值删除、按索引删除、...

Python 中的前缀删除操作全指南(python删除前导0)

1.字符串前缀删除1.1使用内置方法Python提供了几种内置方法来处理字符串前缀的删除:#1.使用removeprefix()方法(Python3.9+)text="...

每天学点Python知识:如何删除空白

在Python中,删除空白可以分为几种不同的情况,常见的是针对字符串或列表中空白字符的处理。一、删除字符串中的空白1.删除字符串两端的空白(空格、\t、\n等)使用.strip()方法:s...

Linux系统自带Python2&amp;yum的卸载及重装

写在前面事情的起因是我昨天在测试Linux安装Python3的shell脚本时,需要卸载Python3重新安装一遍。但是通过如下命令卸载python3时,少写了个3,不小心将系统自带的python2也...

如何使用Python将多个excel文件数据快速汇总?

在数据分析和处理的过程中,Excel文件是我们经常会遇到的数据格式之一。本文将通过一个具体的示例,展示如何使用Python和Pandas库来读取、合并和处理多个Excel文件的数据,并最终生成一个包含...

【第三弹】用Python实现Excel的vlookup功能

今天继续用pandas实现Excel的vlookup功能,假设我们的2个表长成这样:我们希望把Sheet2的部门匹在Sheet1的最后一列。话不多说,先上代码:importpandasaspd...

python中pandas读取excel单列及连续多列数据

案例:想获取test.xls中C列、H列以后(当H列后列数未知时)的所有数据。importpandasaspdfile_name=r'D:\test.xls'#表格绝对...

取消回复欢迎 发表评论: