Python Static method vs class method

本文详细解释了Python中的静态方法和类方法的区别与用途,通过实例展示了它们在解析日期字符串、创建可继承的构造函数等方面的使用场景。

Static method vs class method in Python 

标签: python
  970人阅读  评论(0)  收藏  举报
  分类:
 

Python中@static method@class method对于刚接触的人而言,有很多迷茫的地方。随之,搜索了一些文章,然后整理如下:

@staticmethod function is nothing more than a function definedinside a class. It is callable without instantiating the class first. The definition is immutable via inheritance.

@classmethod function also callable without instantiating the class,but its definition follows Sub class, not Parent class, via inheritance, can be overridden bysubclass. That’s because thefirst argument for @classmethodfunction must always be cls (class).

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class A(object):  
  2.     def foo(self,x):  
  3.         print "executing foo(%s,%s)"%(self,x)  
  4.  
  5.     @classmethod  
  6.     def class_foo(cls,x):  
  7.         print "executing class_foo(%s,%s)"%(cls,x)  
  8.  
  9.     @staticmethod  
  10.     def static_foo(x):  
  11.         print "executing static_foo(%s)"%x      
  12.   
  13. a=A()  

With classmethods, the class of the object instance is implicitly passed as thefirst argument instead of self.

a.class_foo(1)

A.class_foo(1)

One use people havefound for class methods is to create inheritable alternative constructors.

-----------------------------------------------------------------------------------------------------------------------------

With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. Theybehave like plain functions except that you can call them from an instance orthe class:

a.static_foo(1)

A.static_foo('hi')

Staticmethods are usedto group functions which have some logical connection with a class to the class

======================================================================

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class Date(object):  
  2.     day = 0  
  3.     month = 0  
  4.     year = 0  
  5.   
  6.     def __init__(self, day=0, month=0, year=0):  
  7.         self.day = day  
  8.         self.month = month  
  9.         self.year = year  

So what we must do hereis:

1.   Parse a string toreceive day, month and year as thee integer variables or a 3-item tupleconsisting of that variable.

2.   Instantiate Date by passing those values to initialization call.

This will look like:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. day, month, year = map(int, string_date.split('-'))  
  2. date1 = Date(day, month, year)  

For this purpose, C++ has such feature as overloading, but Pythonlacks that feature- so here's when classmethod applies.Let’s create another "constructor".

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @classmethod  
  2. def from_string(cls, date_as_string):  
  3.     day, month, year = map(int, date_as_string.split('-'))  
  4.     date1 = cls(day, month, year)  
  5.     return date1  
  6.   
  7. 2 = Date.from_string('11-09-2012')  

Let's look morecarefully at the above implementation, and review what advantages we have here:

1.   We've implemented datestring parsing in one place and it's reusable now.

2.   Encapsulation works finehere (if you think that you could implement string parsing as a single functionelsewher, this solution fits OOP paradigm far better).

3.   cls is an object that holds class itself, not an instance of the class. It's prettycool because if we inherit our Date class, allchildren will have from_string defined also.


Summary:

@classmethod

1.   Factory method. That are used to create an instance for a classusing for example some sort of preprocessing.

2.   Static method calling static methods. If you split a static methodin several static methods, you shouldn’t hard-code the class name but use classmethods.

@staticmethod

1.    Avoid thecost of instantiate a bound-method for each object.

2.    The methoddoes not depend on the state of object itself.

3.    Method override.


Ref

http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for

http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python

http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner

http://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值