静态方法和类方法在python2.2中被引用,经典类和新式类都可以使用。同时,一对内建函数:staticmethod和classmethod被引入,用来转化类中某一方法为这两种方法之一。

静态方法:

静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,主要是一些逻辑属于类,但是和类本身没有交互,即在静态方法中,不会涉及到类中的方法和属性的操作。可以理解为将静态方法存在此类的名称空间中。事实上,在python引入静态方法之前,通常是在全局名称空间中创建函数。

例子:

譬如,我想定义一个关于时间操作的类,其中有一个获得当前时间的函数。

import time
class TimeTest(object):
def __init__(self,hour,minute,second):
self.hour = hour
self.minute = minute
self.second = second
@staticmethod
def showTime():
return time.strftime("%H:%M:%S", time.localtime()) print TimeTest.showTime()
t = TimeTest(2,10,10)
nowTime = t.showTime()
print(nowTime)

  如上,使用静态函数,既可以将获得时间的函数功能与实例解绑,我想获得当前时间的字符串时,并不一定需要实例化对象,此时更像是一种名称空间。

我们可以在类外面写一个简单的方法来做这些,但是这样做就扩散了类代码的关系到类定义的外面,这样写就会导致以后代码维护的困难。

静态函数可以通过类名以及实例两种方法调用!

类方法:

类方法是将类本身作为对象进行操作的方法。他和静态方法的区别在于:不管这个方式是从实例调用还是从类调用,它都用第一个参数把类传递过来

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner/12179325#12179325

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

应用:

1、做一个颜色的动态匹配

class ColorTest(object):
color = "color"
@classmethod
def value(self):
return self.color class Red(ColorTest):
color = "red" class Green(ColorTest):
color = "green" g = Green()
print g.value()
print Green.value()

  其中,基类做一个抽象共性,对于实际的颜色的值需要结合实际的类进行匹配。

2、假设我有一个学生类和一个班级类,想要实现的功能为:

班级类含有类方法:

执行班级人数增加的操作、获得班级的总人数

学生类继承自班级类,每实例化一个学生,班级人数都能增加。

最后,我想定义一些学生,然后获得班级中的总人数。

思考:这个问题用类方法做比较合适,因为我实例化的时学生,但是如果我从学生这一个实例中获得班级总人数是不合理的。

同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。

class ClassTest(object):
__num = 0
@classmethod
def addNum(self):
self.__num += 1
@classmethod
def getNum(self):
return self.__num def __new__(self):
ClassTest.addNum()
return super(ClassTest,self).__new__(self) class Student(ClassTest):
def __init__(self):
self.name = '' a = Student()
b = Student()
ClassTest.getNum()

  这里我用到魔术函数__new__,主要是为了在创建实例的时候调用人数累加的函数。

类函数可以通过类名以及实例两种方法调用!

注意:

python2 中,必须总要把一个方法声明为静态的,从而能够不带一个实例而调用它。

python3 中,如果方法只通过类调用,而不需要通过实例调用的话,不用非要声明为静态的。

class test:
  def show():
    print ("show")
 
test.show()

  此时会出现错误:

[root@localhost home]# ./test.py
Traceback (most recent call last):
File "./test.py", line 6, in <module>
test.show()
TypeError: unbound method show() must be called with test instance as first argument (got nothing instead)

改到python3即可:

class test:
  def show():
    print ("show")
 
test.show()

python静态方法和类方法的更多相关文章

  1. python 静态方法、类方法(二)

    <Python静态方法.类方法>一文中曾用在类之外生成函数的方式,来计算类的实例的个数.本文将探讨用静态方法和类方法来实现此功能. 一使用静态方法统计实例 例1.static.py # - ...

  2. Python 静态方法、类方法和属性方法

    Python 静态方法.类方法和属性方法 静态方法(staticmethod) staticmethod不与类或者对象绑定,类和实例对象都可以调用,没有自动传值效果,Python内置函数staticm ...

  3. Python 静态方法、类方法

    今天我们来讨论一下Python类中所存在的特殊方法--静态方法.类方法. 一.定义 静态方法: 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静 ...

  4. python 静态方法,类方法 ,类的继承

    转自:  http://cowboy.1988.blog.163.com/blog/static/75105798201091141521583/ 1.关于定义类的一些奇特之处  今天在Python中 ...

  5. Python 静态方法,类方法,属性方法

    方法的使用 静态方法 - 只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性. class Dog(object): def __init__(self,name): self.nam ...

  6. python静态方法、类方法

    常规: class Dog(object): def __init__(self,name): self.name=name def eat(self): print('%s is eating'%s ...

  7. Python 静态方法和类方法的区别

    python staticmethod and classmethod Though classmethod and staticmethod are quite similar, there’s a ...

  8. Python静态方法、类方法、属性方法

    静态方法 使用静态方法以后,相当于把下面的函数和类的关系截断了,它的作用相当于是类下面的一个独立函数,不会自动传入参数self. class people:..... @staticmethod de ...

  9. python 静态方法,类方法,类下面的函数区别

    @clssmenthod(类方法) 与 @staticmethod(静态方法) 与类下面的函数的区别: 1.@classmethod修饰的方法def name(cls)需要通过cls参数传递当前类本身 ...

随机推荐

  1. Qt QLineEdit

    //lineEdit显示文字 QLineEdit *lineEdit = new QLineEdit(widget); lineEdit->setObjectName(QString()); l ...

  2. ajax 的json格式

    我们平时使用ajax向后台传递数据时,通常会传递json格式的数据,当然这里还有其它格式,比如xml.html.script.text.jsonp格式. json类型的数据包含json对象和json类 ...

  3. C# 动态调用泛型方法

    static void Main(string[] args) { #region 具体类型可传递. Personal specifiedPersonal = new Personal(); Empl ...

  4. ContOS7切换国内源

    ContOS更换国内下载源 一,什么是yum源? yum,是Yellow dog Updater, Modified 的简称,是杜克大学为了提高RPM 软件包安装性而开发的一种软件包管理器.起初是由y ...

  5. 【BZOJ3236】【AHOI2013】作业 线段树 分治 树状数组

    题目描述 给你一个长度为\(n\)的数列,还有\(m\)个询问,对于每个询问\((l,r,a,b)\),输出1.区间\([l,r]\)有多少范围在\([a,b]\)的数:2.区间\([l,r]\)有多 ...

  6. SQL循环语句 详解

    SQL循环语句 declare @i int set @i=1 while @i<30 begin insert into test (userid) values(@i) set @i=@i+ ...

  7. Logger.error方法之打印错误异常的详细堆栈信息

    一.问题场景 使用Logger.error方法时只能打印出异常类型,无法打印出详细的堆栈信息,使得定位问题变得困难和不方便. 二.先放出结论 Logger类下有多个不同的error方法,根据传入参数的 ...

  8. 【转】分享两个基于MDK IDE的调试输出技巧

    我们在STM32开发调试过程中,常常需要做些直观的输出,如果手头没有相关的设备或仪器,我们可以使用 IDE自带的工具.这里分享两个基于MDK  IDE的调试输出技巧. 一.使用其自带的逻辑分析仪查看波 ...

  9. PyCharmMarkdown插件的方法

    arkdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式. 从github下载的代码一般都会带有README.md文件,该文件是一个Markdo ...

  10. 【Linux】linux正则表达式及通配符

    正则表达式就是用于匹配每行输入的一种模式,模式是指一串字符序列.拥有强大的字符搜索功能.也非常方便的搜索过滤出我们想要的内容. linux正则表达式分为基本正则表达式(Basic Regexp)和扩展 ...