Python:staticmethod vs classmethod
Being educated under Java background, static method and class method are the same thing.
But not so in Python, there is subtle difference:
Say function a() is defined in Parent Class, while Sub Class extends Parent Class
- If function a() has @staticmethod decorator, Sub.a() still refers to definition inside Parent Class. Whereas,
- If function a() has @classmethod decorator, Sub.a() will points definition inside Sub Class.
Let’s talk about some definitions here:
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).
Let's assume an example of a class, dealing with date information (this is what will be our boilerplate to cook on):
classDate(object):
day =0
month =0
year =0
def __init__(self, day=0, month=0, year=0):self.day = day
self.month = month
self.year = year
This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).
Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typicalinstancemethod, having the first non-optional argument (self) that holds reference to a newly created instance.
Classmethod
We have some tasks that can be nicely done using classmethods.
Let's assume that we want to create a lot of Date class instances having date information coming from outer source encoded as a string of next format ('dd-mm-yyyy'). We have to do that in different places of our source code in project.
So what we must do here is:
- Parse a string to receive day, month and year as thee integer variables or a 3-item tuple consisting of that variable.
- Instantiate
Dateby passing those values to initialization call.
This will look like:
day, month, year = map(int, string_date.split('-'))
date1 =Date(day, month, year)
For this purpose, C++ has such feature as overloading, but Python lacks that feature- so here's whenclassmethod applies. Lets create another "constructor".
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)return date1
date2 =Date.from_string('11-09-2012')
Let's look more carefully at the above implementation, and review what advantages we have here:
- We've implemented date string parsing in one place and it's reusable now.
- Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewher, this solution fits OOP paradigm far better).
clsis an object that holds class itself, not an instance of the class. It's pretty cool because if we inherit ourDateclass, all children will havefrom_stringdefined also.
Staticmethod
What about staticmethod? It's pretty similar to classmethod but doesn't take any obligatory parameters (likeclassmethod or instancemethod does).
Let's look at the next use case.
We have a date string that we want to validate somehow. This task is also logically bound to Date class we've used so far, but still doesn't require instantiation of it.
Here is where staticmethod can be useful. Let's look at the next piece of code:
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))try:assert0<= day <=31assert0<= month <=12assert0<= year <=3999exceptAssertionError:returnFalsereturnTrue
So, as we can see from usage of staticmethod, we don't have any access to what the class is- it's basically just a function, called syntactically like a method, but without access to the object and it's internals (fields and another methods), while classmethod does.
Ref:
http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for
http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner
http://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
Python:staticmethod vs classmethod的更多相关文章
- Python语言特性之3:@staticmethod和@classmethod
问题:Python中@staticmethod和@classmethod两种装饰器装饰的函数有什么不同? 原地址:http://stackoverflow.com/questions/136097/w ...
- 基于python中staticmethod和classmethod的区别(详解)
例子 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 class A(object): def foo(self,x): print "executing foo ...
- 面试题:python 中 staticmethod 和 classmethod有什么区别
面试中经常会问到staticmethod 和 classmethod有什么区别? 首先看下官方的解释: staticmethod: class staticmethod staticmethod(fu ...
- python中@staticmethod与@classmethod
@ 首先这里介绍一下‘@’的作用,‘@’用作函数的修饰符,是python2.4新增的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行.只可以对模块或者类定义的函数进行修饰,不允许修饰一个 ...
- python 之@staticmethod和@classmethod
在python中,要调用一个类中的方法,一般的操作步骤如下: 1.实例化此类 2.调用此类中的方法 而@staticmethod和@classmethod则打破了这种引用方式,可以在不实例化类的情况下 ...
- python中 staticmethod与classmethod
原文地址https://blog.csdn.net/youngbit007/article/details/68957848 原文地址https://blog.csdn.net/weixin_3565 ...
- Python - 静态函数(staticmethod), 类函数(classmethod), 成员函数 区别(完全解析)
原文地址:http://blog.csdn.net/caroline_wendy/article/details/23383995 还有一篇:http://blog.csdn.net/carolzha ...
- 【Python】@staticmethod和@classmethod的作用与区别
前言 Python其实有3个方法,即静态方法(staticmethod),类方法(classmethod)和实例方法,一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法.而使用@static ...
- python 中 staticmethod 和 classmethod有什么区别
面试中经常会问到staticmethod 和 classmethod有什么区别? 首先看下官方的解释: staticmethod: class staticmethod staticmethod(fu ...
随机推荐
- java的clone
做项目时有时可能会遇到需要克隆对象的时候,因为有时候对象是直接从别的类get到的,那样引用的是一个对象,修改的话会将原先的对象也修改了. java的浅克隆,十分简单.但是只会克隆基本的数据类型,当涉及 ...
- 深入研究B树索引(一)
摘要:本文对B树索引的结构.内部管理等方面做了一个全面的介绍.同时深入探讨了一些与B树索引有关的广为流传的说法,比如删除记录对索引的影响,定期重建索引能解决许多性能问题等. 1.B树索引的相关概念 索 ...
- php 变量
unset() 卸载 静态变量static $i=2; 1.是在所有对函数调用中共享; 2.只有在第一次调用的时候赋值 <?php /* * 一.任何数量的参数 * func_get-args( ...
- ListView的小知识
1.设置项目分割功能 android:divider="@android:color/blue" android:dividerHeight="10dp" &l ...
- Android的Drawable
1.获取Drawable的内部宽\高:getIntrinsicHeight/Width.但是并不是所有Drawable都有内部宽高(比如说一个颜色形成的宽高,Drawable的宽高不等于大小,大小是根 ...
- 【C语言】单片机上的按键检测框架
又好久没来写blog,最近在做项目发现之前写的stm32操作都忘了,还好做了个记录,回来看了下很多忘了的就又知道怎么做了. 下面是我之前写的一个按键检测的框架,适合比较多的按键操作,从信号接收.滤波. ...
- Oracle EBS-SQL (PO-14):检查供应商信息sql
select pvs.org_id, pvs.vendor_id, pvs.vendor_site_id, hou.name 经营组织, ...
- 复习完毕STM32开发板
经过半个晚上的折腾,终于复习了STM32开发板,并使用ST官方库调试完毕一个printf重定向到串口的程序,3.5的库同以前的库不大一样,不过最终搞好了可以睡觉了,还可以睡7个小时. ...
- hdu 2102 A计划_bfs搜索
题意:略 思路:此题陷阱超多,当##,#*,*#时不能走进去,套下模板就行了. #include <iostream> #include<cstdio> #include< ...
- 下载类网站的SEO优化方面技巧
在互联网国际中有一类十分主要的网站,那即是供应各种软件下载的网站,这类网站可以协助用户解决许多软件运用方面的疑问,可是随着知识产权维护的认识越来越强,许多下载类网站也要开端改动自个的经营策略,这么才可 ...