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

相关文章

Python二进制文件读取并转换为浮点数详解

Python二进制文件读取并转换为浮点数详解

本文所用环境: Python 3.6.5 |Anaconda custom (64-bit)| 引言 由于某些原因,需要用python读取二进制文件,这里主要用到struct包,而这...

Django框架下在视图中使用模版的方法

 打开current_datetime 视图。 以下是其内容: from django.http import HttpResponse import datetime...

Python利用heapq实现一个优先级队列的方法

Python利用heapq实现一个优先级队列的方法

实现一个优先级队列,每次pop的元素要是优先级高的元素,由于heapq.heapify(list)默认构建一个小顶堆,因此要将priority变为相反数再push,代码如下: imp...

Python使用gensim计算文档相似性

pre_file.py #-*-coding:utf-8-*- import MySQLdb import MySQLdb as mdb import os,sys,string i...

如何给Python代码进行加密

这篇文章主要介绍了如何给Python代码进行加密,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 去年11月在PyCon China 2...