Static method vs class method in Python

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).

class A(object):
    def foo(self,x):
        print "executing foo(%s,%s)"%(self,x)

    @classmethod
    def class_foo(cls,x):
        print "executing class_foo(%s,%s)"%(cls,x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)"%x    

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

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

class Date(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

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:

day, month, year = map(int, string_date.split('-'))
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".

    @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 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






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值