关于“Python的静态方法”很多学习py的同学不太了解,今天幕客就来总结下。
python的静态方法仅在类中出现,和许多语言(C、JAVA)的静态方法一样。有了静态方法我们能方便的用类直接调用方法,可以不用先实例化的优点。即使子类,也可议改写父类中的静态方法。
下面幕客用两个例子。
一、说下调用类的静态方法,可以不用先实例化
python的静态方法仅仅是类的函数(注意:是类的函数,不是实例的),所以我们调用类的静态方法,可以不用先实例化,然后直接调用,如下:
In [30]: class Myclass( ):
...: @staticmethod
...: def static_method(x):
...: print "static method echo....",x
...:
In [31]: Myclass.static_method('imoocc')
static method echo.... imoocc
但方法不是静态方法,是不可以调用的,如下:
In [34]: class Myclass( ):
...: def normal_method(x):
...: print "normal method echo ...",x
...:
In [35]: sm = Myclass()
In [36]: Myclass.normal_method('imoocc')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 Myclass.normal_method('2')
TypeError: unbound method normal_method() must be called with Myclass instance as first argument (got str instance instead)
二、父类中的静态方法可议通过子类重新定制
In [5]: class childclass(Myclass):
...: @staticmethod
...: def normal_method(x):
...: print "child method echo ...",x
...:
In [6]: childclass.normal_method('imoocc')
child method echo ... imoocc
关注幕客技术,将提供更多的python技术知识~
鼓励一句:
Money is not the problem, the problem is money!
继续阅读与本文标签相同的文章
【剑指offer】二叉树中和为某一值的路径
记录一次排查netty堆内存泄漏经历
-
斩获2019中国金融科技创新大赛金奖,蚂蚁金服mPaaS助力打造超级App生态
2026-05-19栏目: 教程
-
有呀!互联网icp许可证除申请以外有转让的吗?飞起
2026-05-19栏目: 教程
-
Apache Zepplin使用Hive Interpreter查询
2026-05-19栏目: 教程
-
大宗货运如何实现“重去重回”?
2026-05-19栏目: 教程
-
企业官网怎么选择合适的阿里云服务器ECS(新手参考)
2026-05-19栏目: 教程
