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?

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/archive/2011/07/04/2097646.html
相关文章
|
24天前
|
Java 程序员 索引
Python中魔术方法汇总
Python中魔术方法汇总
19 0
|
4月前
|
Python
python静态方法
python静态方法
39 0
|
5月前
|
Java PHP Python
小记Python中一些常用的魔术方法
小记Python中一些常用的魔术方法
14 0
|
6月前
|
Python
Python魔术方法大全1
在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”(魔术方法),例如类的初始化方法 init ,Python中所有的魔术方法均在官方文档中有相应描述,这边给大家把所有的魔术方法汇总了一下,希望对大家的学习有所帮助。
36 0
|
6月前
|
Java API 数据安全/隐私保护
Python魔术方法大全2
在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”(魔术方法),例如类的初始化方法 init ,Python中所有的魔术方法均在官方文档中有相应描述,这边给大家把所有的魔术方法汇总了一下,希望对大家的学习有所帮助。
20 0
|
6月前
|
存储 C语言 Python
Python魔术方法大全3
在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”(魔术方法),例如类的初始化方法 init ,Python中所有的魔术方法均在官方文档中有相应描述,这边给大家把所有的魔术方法汇总了一下,希望对大家的学习有所帮助。
43 0
|
8月前
|
Python
【从零学习python 】45.Python中的类方法和静态方法
【从零学习python 】45.Python中的类方法和静态方法
54 0
|
10月前
|
PyTorch 算法框架/工具 索引
Python 实例方法
Python 实例方法
|
11月前
|
Python
|
12月前
|
Python
一篇文章告诉你什么是 Python 元类
一篇文章告诉你什么是 Python 元类
38 0