静态方法和类方法在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. Civil 3D 二次开发 创建AutoCAD对象—— 01 —— 创建直线

    在方法CreateLine内完成以下代码: 01 public void CreateLine() 02 { 03 PromptPointOptions ppo = new PromptPointOp ...

  2. UOJ274 [清华集训2016] 温暖会指引我们前行 【LCT】【最大生成树】

    题目分析: 差评,最大生成树裸题.hack数据还卡常. 代码: #include<bits/stdc++.h> using namespace std; ; struct LCT{ ],d ...

  3. Android学习第7天

    这次大都是广播案例,在笔记中不予展示注: a.做开机启动时,在广播类中用到Intent需要这三行代码 Intent intent1 = new Intent(context, MainActivity ...

  4. python通过配置文件连接数据库

    今天主要是通过读取配置文件(ini文件)获取数据库表的ip,端口,用户,密码,表名等,使用pysql来操作数据库,具体的ini配置文件的操作参见我另一篇博客:https://www.cnblogs.c ...

  5. IOS端 margin-top 和 margin-bottom 使用负数时的区别

    有以下html代码 <div style="width: 30%;" class="shang"> 1 </div> <div s ...

  6. Hdoj 1374.Knight Moves 题解

    Problem Description A friend of you is doing research on the Traveling Knight Problem (TKP) where yo ...

  7. 【BZOJ5291】[BJOI2018]链上二次求和(线段树)

    [BZOJ5291][BJOI2018]链上二次求和(线段树) 题面 BZOJ 洛谷 题解 考虑一次询问\([l,r]\)的答案.其中\(S\)表示前缀和 \(\displaystyle \sum_{ ...

  8. poj3926 parade (单调队列+dp)

    题意:有n行路,每行路被分成m段,每一段有长度和权值,要求从最下面一行走到最上面一行某个位置,可以从相邻两行的同一列交点往上走,并且在同一行走的长度要<=K,求走过的最大权值 设f[i][j]为 ...

  9. RHEL7 下双网卡绑定做主备(冗余)

    应用环境:在生产环境中,为了提高网络容错或吞吐量,一般服务器都会采取多网卡绑定的策略(此处只讲主备模式).  在RedHat 6.x下一般叫网卡做“bond”,在7.x版本中改名叫“Team”. 测试 ...

  10. Centos 7下下载和安装docker

    sudo yum install -y device-mapper sudo modprobe dm_mod ls -l /sys/class/misc/device-mapper sudo rpm ...