龙空技术网

关于python的静态方法(演示)

幕客技术 231

前言:

今天我们对“python静态变量和静态方法”大约比较关怀,看官们都需要了解一些“python静态变量和静态方法”的相关文章。那么小编在网络上收集了一些对于“python静态变量和静态方法””的相关资讯,希望同学们能喜欢,小伙伴们快快来学习一下吧!

关于“Python的静态方法”很多学习py的同学不太了解,今天幕客来总结下。

python的静态方法在仅在类中出现,和许多语言(C、JAVA)的静态方法一样。有了静态方法我们能方便的实现调用类的静态方法,可以不用先实例化的优点。及时子类,也可议改写父类中的静态方法。

下面幕客用两个例子。

一、说下调用类的静态方法,可以不用先实例化

python的静态方法仅仅是类的函数(注意:是类的函数,不是实例的),所以我们调用类的静态方法,可以不用先实例化,然后直接调用,如下:

In [30]: class Myclass(object):

...: @staticmethod

...: def static_method(x):

...: print "static method echo....",x

...:

In [31]: Myclass.static_method('imoocc')

static method echo.... imoocc

但方法不是静态方法,是不可以调用的,如下:

In [34]: class Myclass(object):

...: 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)

<ipython-input-36-602ebd3eb207> in <module>()

----> 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技术知识~

标签: #python静态变量和静态方法