Magic Studio

专心做有逼格的APP!

Python的类方法

I used to work with PHP and recently I was asking myself, whats going on with this classmethod? Python manual is very technical and very short in words so it wont help with understanding that feature. I was googling and googling and I found answer -> http://code.anjanesh.net/2007/12/python-classmethods.html.

If you are lazy to click it. My explanation is shorter and below. :)

in PHP (maybe not all of you know PHP, but this language is so straight forward that everybody should understand what I'm talking about) we have static variables like this:


class A
{

   
static protected $inner_var = null;

   
static public function echoInnerVar()
   
{
        echo
self::$inner_var."\n";
   
}

   
static public function setInnerVar($v)
   
{
       
self::$inner_var = $v;
   
}

}

class B extends A
{
}

A
::setInnerVar(10);
B
::setInnerVar(20);

A
::echoInnerVar();
B
::echoInnerVar();

The output will be in both cases 20.

However in python we can add @classmethod decorator and thus it is possible to have output 10 and 20 respectively. Example:


class A(object):
    inner_var
= 0

   
@classmethod
   
def setInnerVar(cls, value):
        cls
.inner_var = value

   
@classmethod
   
def echoInnerVar(cls):
       
print cls.inner_var


class B(A):
   
pass


A
.setInnerVar(10)
B
.setInnerVar(20)

A
.echoInnerVar()
B
.echoInnerVar()

Smart, ain't?

posted on 2011-07-04 18:03  Mr 布鲁斯  阅读(198)  评论(0编辑  收藏  举报

导航