首页
学习
活动
专区
工具
TVP
发布

关于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)

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!

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20171208G0ZNQH00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券