建站宝盒合作,网站手机版如何制作,网站开发与维护前景,那曲地区建设局网站这里先说结论#xff0c;为了满足心急的小伙伴#xff1a;method与function的最大区别就是参数有无进行绑定。 自定义类Test#xff1a;
首先先来一个自定义类#xff1a;
class Test:def Func_normal(arg):print(Func_normal:,arg)staticmethoddef Func_static(arg):pri…这里先说结论为了满足心急的小伙伴method与function的最大区别就是参数有无进行绑定。 自定义类Test
首先先来一个自定义类
class Test:def Func_normal(arg):print(Func_normal:,arg)staticmethoddef Func_static(arg):print(Func_static:,arg)classmethoddef Func_class(arg):print(Func_class:,arg)代码样例
先来一份代码以及运行结果
objTest()#Test为本文开头提到的自定义类
for item in [Test,obj]:print(\n(classif itemTest else object))for name in [normal,static,class]:print(f[{name}],eval(f{item}.Func_{name}))为了更直观地看出差别这里简单的编写一个表格
属性访问[normal][staticmethod][classmethod]classfunctionfunctionmethod-classobjectmethod-objectfunctionmethod-class
可以看出通过类和通过对象访问到的是不完全一致的而这与本主题有关。 但是仅仅通过这个还不够直观地表现出它们的差异性这里再附加一份测试代码以及运行结果
objTest()#Test为本文开头提到的自定义类
for item in [Test,obj]:for name in [normal,static,class]:try:txf{item}.Func_{name}()print(,tx)exec(tx)except Exception as e:print(e)print()这里同样贴心地将上面的结果整理成表格便于对比
不传参数[normal][staticmethod][classmethod]class错误缺失1参错误缺失1参classobjectobject错误缺失1参class 分析
在上面的代码样例中得到两张表格这里再重新把俩表格放在一起以便进行对比请仔细比对俩表格之间的差异。
属性访问[normal][staticmethod][classmethod]classfunctionfunctionmethod-classobjectmethod-objectfunctionmethod-class
不传参数[normal][staticmethod][classmethod]class错误缺失1参错误缺失1参classobjectobject错误缺失1参class
以下为结论
method与function的最大区别就是参数有无进行绑定。在本例中method在调用时不需要参数因为第一个参数已经与特定对象进行了绑定而function需要传入1参数才能正常调用。classmethod的作用是将函数的第一个参数绑定为本类(无论是通过类还是类对象进行调用)staticmethod的作用则是撤去第一个参数的绑定。 完整代码
class Test:def Func_normal(arg):print(Func_normal:,arg)staticmethoddef Func_static(arg):print(Func_static:,arg)classmethoddef Func_class(arg):print(Func_class:,arg)objTest()
for item in [Test,obj]:print(\n(classif itemTest else object))for name in [normal,static,class]:print(f[{name}],eval(f{item}.Func_{name}))print(\n\n——*30\n\n)objTest()
for item in [Test,obj]:for name in [normal,static,class]:try:txf{item}.Func_{name}()print(,tx)exec(tx)except Exception as e:print(e)print()本文发布于CSDN未经本人同意不得私自转载https://blog.csdn.net/weixin_44733774/article/details/133509177