python的类方法和静态方法

yipeiwu_com5年前Python基础

本文实例讲述了python的类方法和静态方法。分享给大家供大家参考。具体分析如下:

python没有和C++中static关键字,它的静态方法是怎样的呢?还有其它语言中少有的类方法又是神马?

python中实现静态方法和类方法都是依赖于python的修饰器来实现的。

复制代码 代码如下:
class MyClass:
 
    def  method(self):
           print("method")
 
    @staticmethod
    def  staticMethod():
            print("static method")
 
     @classmethod
     def classMethod(cls):
           print("class method")

大家注意到普通的对象方法、类方法和静态方法的去别了吗?
对象方法有self参数,类方法有cls参数,静态方法是不需要这些附加参数的。
在C++中是没有类方法着个概念的的

复制代码 代码如下:

class A(object):
    "This ia A Class"

    @staticmethod
    def Foo1():
        print("Call static method foo1()\n")

    @classmethod
    def Foo2(cls):
        print("Call class method foo2()")
        print("cls.__name__ is ",cls.__name__)

A.Foo1();
A.Foo2();

结果是:
Call static method foo1()

Call class method foo2()
cls.__name__ is  A

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Mac 使用python3的matplot画图不显示的解决

Mac 使用python3的matplot画图不显示的解决

最近用matplot画图,使用plt.show()无反应,网上冲浪发现是matplotlib后端问题,使用matplotlib.get_backend()命令查看当前绘图后端: 参数为...

在Python中使用matplotlib模块绘制数据图的示例

在Python中使用matplotlib模块绘制数据图的示例

 matplotlib是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序...

python生成指定长度的随机数密码

复制代码 代码如下:#!/usr/bin/env python# -*- coding:utf-8 -*- #导入random和string模块import random, string...

pandas对指定列进行填充的方法

实例如下所示: >>> import pandas as pd >>> import numpy as np >>> ts1 =...

Python判断一个list中是否包含另一个list全部元素的方法分析

本文实例讲述了Python判断一个list中是否包含另一个list全部元素的方法。分享给大家供大家参考,具体如下: 你可以用for in循环+in来判断 #!/usr/bin/env...