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

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

off999 2024-09-20 22:49 27 浏览 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文件操作与输入输出

9.1文件的基本操作9.1.1打开文件理论知识:在Python中,使用open()函数来打开文件。open()函数接受两个主要参数:文件名和打开模式。打开模式决定了文件如何被使用,常见的模式有:&...

Python的文件处理

一、文件处理的流程1.打开文件,得到文件句柄并赋值给一个变量2.通过句柄对文件进行操作3.关闭文件示例:d=open('abc')data1=d.read()pri...

Python处理文本的25个经典操作

Python处理文本的优势主要体现在其简洁性、功能强大和灵活性。具体来说,Python提供了丰富的库和工具,使得对文件的读写、处理变得轻而易举。简洁的文件操作接口Python通过内置的open()函数...

Python学不会来打我(84)python复制文件操作总结

上一篇文章我们分享了python读写文件的操作,主要用到了open()、read()、write()等方法。这一次是在文件读写的基础之上,我们分享文件的复制。#python##python自学##...

python 文件操作

1.检查目录/文件使用exists()方法来检查是否存在特定路径。如果存在,返回True;如果不存在,则返回False。此功能在os和pathlib模块中均可用,各自的用法如下。#os模块中e...

《文件操作(读写文件)》

一、文件操作基础1.open()函数核心语法file=open("filename.txt",mode="r",encoding="utf-8"...

栋察宇宙(二十一):Python 文件操作全解析

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“Python文件操作全解析”欢迎您的访问!Sharethefun,spreadthe...

值得学习练手的70个Python项目(附代码),太实用了

Python丰富的开发生态是它的一大优势,各种第三方库、框架和代码,都是前人造好的“轮子”,能够完成很多操作,让你的开发事半功倍。下面就给大家介绍70个通过Python构建的项目,以此来学习Pytho...

python图形化编程:猜数字的游戏

importrandomnum=random.randint(1,500)running=Truetimes=0##总的次数fromtkinterimport*##导入所有tki...

一文讲清Python Flask的Web编程知识

刚入坑Python做Web开发的新手,还在被配置臃肿、启动繁琐折磨?Flask这轻量级框架最近又火出圈,凭5行代码启动Web服务的极致简洁,让90后程序员小张直呼真香——毕竟他刚用这招把部署时间从半小...

用python 编写一个hello,world

第一种:交互式运行一个hello,world程序:这是写python的第一步,也是学习各类语言的第一步,就是用这种语言写一个hello,world程序.第一步,打开命令行窗口,输入python,第二步...

python编程:如何使用python代码绘制出哪些常见的机器学习图像?

专栏推荐绘图的变量单变量查看单变量最方便的无疑是displot()函数,默认绘制一个直方图,并你核密度估计(KDE)sns.set(color_codes=True)np.random.seed(su...

如何编写快速且更惯用的 Python 代码

Python因其可读性而受到称赞。这使它成为一种很好的第一语言,也是脚本和原型设计的流行选择。在这篇文章中,我们将研究一些可以使您的Python代码更具可读性和惯用性的技术。我不仅仅是pyt...

Python函数式编程的详细分析(代码示例)

本篇文章给大家带来的内容是关于Python函数式编程的详细分析(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。FunctionalProgramming,函数式编程。Py...

编程小白学做题:Python 的经典编程题及详解,附代码和注释(七)

适合Python3+的6道编程练习题(附详解)1.检查字符串是否以指定子串开头题目描述:判断字符串是否以给定子串开头(如"helloworld"以"hello&...

取消回复欢迎 发表评论: