暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

python静态方法和类方法

原创 梯阅线条 2023-12-21
241

1 python静态方法和类方法

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)

2 END

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

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

文章转载自梯阅线条,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论