python静态方法和类方法
静态方法和类方法在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)
如上,使用静态函数,既可以将获得时间的函数功能与实例解绑,我想获得当前时间的字符串时,并不一定需要实例化对象,此时更像是一种名称空间。
我们可以在类外面写一个简单的方法来做这些,但是这样做就扩散了类代码的关系到类定义的外面,这样写就会导致以后代码维护的困难。
静态函数可以通过类名以及实例两种方法调用!
类方法:
类方法是将类本身作为对象进行操作的方法。他和静态方法的区别在于:不管这个方式是从实例调用还是从类调用,它都用第一个参数把类传递过来。
@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静态方法和类方法的更多相关文章
- python 静态方法、类方法(二)
<Python静态方法.类方法>一文中曾用在类之外生成函数的方式,来计算类的实例的个数.本文将探讨用静态方法和类方法来实现此功能. 一使用静态方法统计实例 例1.static.py # - ...
- Python 静态方法、类方法和属性方法
Python 静态方法.类方法和属性方法 静态方法(staticmethod) staticmethod不与类或者对象绑定,类和实例对象都可以调用,没有自动传值效果,Python内置函数staticm ...
- Python 静态方法、类方法
今天我们来讨论一下Python类中所存在的特殊方法--静态方法.类方法. 一.定义 静态方法: 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静 ...
- python 静态方法,类方法 ,类的继承
转自: http://cowboy.1988.blog.163.com/blog/static/75105798201091141521583/ 1.关于定义类的一些奇特之处 今天在Python中 ...
- Python 静态方法,类方法,属性方法
方法的使用 静态方法 - 只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性. class Dog(object): def __init__(self,name): self.nam ...
- python静态方法、类方法
常规: class Dog(object): def __init__(self,name): self.name=name def eat(self): print('%s is eating'%s ...
- Python 静态方法和类方法的区别
python staticmethod and classmethod Though classmethod and staticmethod are quite similar, there’s a ...
- Python静态方法、类方法、属性方法
静态方法 使用静态方法以后,相当于把下面的函数和类的关系截断了,它的作用相当于是类下面的一个独立函数,不会自动传入参数self. class people:..... @staticmethod de ...
- python 静态方法,类方法,类下面的函数区别
@clssmenthod(类方法) 与 @staticmethod(静态方法) 与类下面的函数的区别: 1.@classmethod修饰的方法def name(cls)需要通过cls参数传递当前类本身 ...
随机推荐
- .resx文件与.cs文件的自动匹配
图中myCommands.Resx是<DependentUpon> myCommands.cs文件的. 如何为其他的.cs文件添加类似的资源文件呢? 其实挺简单, 添加与.cs文件同名的资 ...
- python史上最全学习路线图
ps:盘它 python入门教程 关注微信公众号,回复"python入门"获取视频下载地址
- Ubuntu基于zsh自定义设置shell主题
为优化Ubuntu命令行页面效果,Google一番选择github上开源项目zsh,以自定义Shell主题,注:本机系统为Ubuntu 14.04 1.安装zsh sudo apt-get insta ...
- Java异步、线程池解决方案
一.ThreadPoolExecutor------线程池 private static final ThreadPoolExecutor threadPoolExecutor = new Threa ...
- Matplotlib学习---用matplotlib画散点图,气泡图(scatter plot, bubble chart)
Matplotlib里有两种画散点图的方法,一种是用ax.plot画,一种是用ax.scatter画. 一. 用ax.plot画 ax.plot(x,y,marker="o",co ...
- 解决sublime text3 中文字符乱码
前言 由于系统编码问题导致的中文乱码解决,linux和windows解决方式都一样. 流程 linux下两步都需要,windows下只需要第二步. 1.在package install中搜索安装:co ...
- 【XSY2523】神社闭店之日 莫比乌斯反演
题目大意 给你\(a_1\ldots a_n,l,c\)每次给你\(x,y\),求有多少个序列满足:长度\(\leq l\),每个元素是\([1,c]\),循环右移\(a_j(x\leq j\leq ...
- flask简单登录注册
效果图 发布问答页面需要登录才能访问,没有登录会跳转到登录页面 模板继承,正则验证,数据库迁移,md5加密 mysql 5.7 登录页面 登录后的发布问答页面,右上角会显示用户名和注销 项目代码:码云
- cf1088C Ehab and a 2-operation task (构造)
题意:给一个数列,你可以进行至多n+1次操作,每次给一个前缀对某数取模或者加某数,使得最后数列严格单增 考虑到因为是前缀和而且还不能加负数,光靠加是不能让前面的小于后面的 所以要让他先在模某数意义下单 ...
- Transactional ejb 事务陷阱
对应ejb,默认是对整个类使用事务.所以所有方法都开启事务. 而对于用TransactionAttribute注释来引用容器管理的事务,只能在第一级的方法中使用.对应类中的方法再调用其它类中方法,注释 ...