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: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!
















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2011/07/04/2097646.html ,如需转载请自行联系原作者
相关文章
|
12天前
|
Python
python魔法方法如何应用
【4月更文挑战第12天】这个Python示例展示了类继承和方法重写。`Student`类继承自`Person`,并覆盖了`say_hello`方法。通过`super().__init__(name)`调用父类的`__init__`初始化`name`属性,`Student`添加了`age`属性,并在重写的`say_hello`中使用。创建`Student`实例`student`并调用其`say_hello`,输出定制的问候信息。
19 1
|
23小时前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
7 0
|
1天前
|
Python
Python 一步一步教你用pyglet制作可播放音乐的扬声器类
Python 一步一步教你用pyglet制作可播放音乐的扬声器类
6 0
|
5天前
|
存储 关系型数据库 MySQL
Python搭建代理IP池实现存储IP的方法
Python搭建代理IP池实现存储IP的方法
|
5天前
|
Python
Python动态IP代理防止被封的方法
Python动态IP代理防止被封的方法
|
6天前
|
数据采集 存储 安全
python检测代理ip是否可用的方法
python检测代理ip是否可用的方法
|
7天前
|
数据可视化 测试技术 Python
在Python和R中使用交叉验证方法提高模型性能
在Python和R中使用交叉验证方法提高模型性能
19 0
|
7天前
|
存储 监控 开发工具
对象存储OSS产品常见问题之python sdk中的append_object方法支持追加上传xls文件如何解决
对象存储OSS是基于互联网的数据存储服务模式,让用户可以安全、可靠地存储大量非结构化数据,如图片、音频、视频、文档等任意类型文件,并通过简单的基于HTTP/HTTPS协议的RESTful API接口进行访问和管理。本帖梳理了用户在实际使用中可能遇到的各种常见问题,涵盖了基础操作、性能优化、安全设置、费用管理、数据备份与恢复、跨区域同步、API接口调用等多个方面。
38 9
|
8天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
48 0
|
8天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
31 0