python的类方法和静态方法

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python单体模式的几种常见实现方法详解

本文实例讲述了Python单体模式的几种常见实现方法。分享给大家供大家参考,具体如下: 这里python实现的单体模式,参考了:https://stackoverflow.com/que...

Python 最强编辑器详细使用指南(PyCharm )

Python 最强编辑器详细使用指南(PyCharm )

作者:Jahongir Rahmonov 机器之心编译 参与:魔王 PyCharm 是一种 Python IDE,可以帮助程序员节约时间,提高生产效率。那么具体如何使用呢?本文从 PyC...

matplotlib实现热成像图colorbar和极坐标图的方法

matplotlib实现热成像图colorbar和极坐标图的方法

热成像图 %matplotlib inline from matplotlib import pyplot as plt import numpy as np def f(x,...

全面理解Python中self的用法

刚开始学习Python的类写法的时候觉得很是麻烦,为什么定义时需要而调用时又不需要,为什么不能内部简化从而减少我们敲击键盘的次数?你看完这篇文章后就会明白所有的疑问。 self代表类的实...

Python 两个列表的差集、并集和交集实现代码

Python 两个列表的差集、并集和交集实现代码

①差集 方法一: if __name__ == '__main__': a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4},...