python中的定义:

  1. class MyClass:
  2. ...
  3. @classmethod  # classmethod的修饰符
  4. def class_method(cls, arg1, arg2, ...):
  5. ...
  6. @staticmethod  # staticmethod的修饰符
  7. def static_method(arg1, arg2, ...):
  8. ...

@classmethod : 类方法

@staticmethod : 静态方法

类方法和静态方法的调用一样,都是通过类就可以直接调用。

区别:类方法,需要传入该类,定义类方法的时候要传一个默认的参数cls。静态方法则不用。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.net
 
class Test(object):
    x = 11
    def __init__(self, _x):
        self._x = _x
        print("Test.__init__")
  
    @classmethod
    def class_method(cls):
        print("class_method")
  
    @staticmethod
    def static_method():
        print("static_method")
  
    @classmethod
    def getPt(cls):
        cls.class_method()
        cls.static_method()
  
if "__main__" == __name__:
    Test.class_method()         # class_method
    Test.static_method()        # static_method
    Test.getPt()                # class_method  static_method
 
    t = Test(22)                # Test.__init__
    t.class_method()            # class_method
    t.static_method()           # static_method
     
    print Test.x                # 11
#     print Test._x
     
    print t.x                   # 11
    print t._x                  # 22
     
#     t.getPr()   # 'Test' object has no attribute 'getPr'

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class_method
static_method
class_method
static_method
Test.__init__
class_method
static_method
11
11
22
Traceback (most recent call last):
  File "/home/homer/workspace/myPython/com/connmiliao.py", line 40, in <module>
    t.getPr()
AttributeError: 'Test' object has no attribute 'getPr'</module>

示例:@property,@staticmethod,@classmethod 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.net
 
class MyClass(object):
    def __init__(self):
        print '__init__'
        self._name = 'blog.ithomer.net'
 
    @staticmethod
    def static_method():
        print 'This is a static method!'
 
    def test(self):
        print 'call test'
 
    @classmethod
    def class_method(cls):
        print 'cls: ',cls
        print 'cls.name: ',cls.name
        print 'cls.static_method(): ',cls.static_method()
        instance = cls()
        print 'instance.test(): ',instance.test()
 
    @property
    def name(self):
        return self._name
     
    @name.setter
    def name(self, value):
        self._name = value
 
if __name__ == '__main__':
    MyClass.static_method()
    MyClass.class_method()
     
    mc = MyClass()
    print mc.name
    mc.name = 'forum.ithomer.net' 
    print mc.name

运行结果:

This is a static method!
cls: <class '__main__.myclass'="">
cls.name: 
cls.static_method(): This is a static method!
None
__init__
instance.test(): call test
None
__init__
blog.ithomer.net
forum.ithomer.net

python -- @classmethod @staticmethod区别和使用的更多相关文章

  1. 【python】classmethod & staticmethod 区别

    来源:http://blog.csdn.net/carolzhang8406/article/details/6856817 其他参考: http://blog.csdn.net/lovingprin ...

  2. python中@classmethod @staticmethod区别

    Python中3种方式定义类方法, 常规方式, @classmethod修饰方式, @staticmethod修饰方式. class A(object): def foo(self, x): prin ...

  3. python中@classmethod @staticmethod区别(转)

    pthon中3种方式定义类方法, 常规方式, @classmethod修饰方式, @staticmethod修饰方式. class A(object): def foo(self, x): print ...

  4. [转]python中@classmethod @staticmethod区别

    Python中3种方式定义类方法, 常规方式, @classmethod修饰方式, @staticmethod修饰方式. class A(object): def foo(self, x): prin ...

  5. django classonlymethod 和 python classmethod的区别

    --classmethod可以被一个实例调用,classonlyethod只能被类调用 class Kls(object): no_inst = 0 def __init__(self): Kls.n ...

  6. 基于python中staticmethod和classmethod的区别(详解)

    例子 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 class A(object):   def foo(self,x):     print "executing foo ...

  7. python @classmethod和@staticmethod区别

    python 类方法和静态方法区别 python @classmethod和@staticmethod区别 Python中至少有三种比较常见的方法类型,即实例方法,类方法.静态方法.它们是如何定义的呢 ...

  8. 模块复习 staticmethod和classmethod的区别

    Python中classmethod与staticmethod区别 classmethod:类方法staticmethod:静态方法 在python中,静态方法和类方法都是可以通过类对象和类对象实例访 ...

  9. python面试题之下面这些是什么意思:@classmethod, @staticmethod, @property?

    回答背景知识 这些都是装饰器(decorator).装饰器是一种特殊的函数,要么接受函数作为输入参数,并返回一个函数,要么接受一个类作为输入参数,并返回一个类. @标记是语法糖(syntactic s ...

随机推荐

  1. redis(7)LRU缓存

    一.LRU简介 LRU是Least Recently Used的缩写,即:最近最少使用. 它是内存管理中的一种页面置换算法,对于在内存中但是又不用的数据块,操作系统会根据哪些数据属于LRU而将其移除内 ...

  2. 微信公众号开发《一》OAuth2.0网页授权认证获取用户的详细信息,实现自动登陆

    原创声明:本文为本人原创作品,绝非他处转账,转载请联系博主 从接触公众号到现在,开发维护了2个公众号,开发过程中遇到很多问题,现在把部分模块功能在这备案一下,做个总结也希望能给其他人帮助 工欲善其事, ...

  3. php获取今日开始时间和结束时间

    $begintime=date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y'))); $endtime=date( ...

  4. sql: T-SQL 统计计算(父子關係,樹形,分級分類的統計)

    ---sql: T-SQL 统计计算(父子關係,樹形,分級分類的統計) ---2014-08-26 塗聚文(Geovin Du) CREATE PROCEDURE proc_Select_BookKi ...

  5. webstorm启动后右下角总有进程在扫描

    启动webstorm后,右下角有一个扫描的任务总在执行,其他操作很卡. 搜索后找到一个办法:在node-modules右键,选择Mark Directory As选择exclude 具体原因没找到.

  6. Javascript 多物体运动1

    多物体运动 <!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <ti ...

  7. Infor SyteLine如何快速锁定用户

    使用Infor Syteline ERP系统,当需要做系统维护时,我们需要通知所有用户退出系统,在维护期间,严禁用户登录,这样的话,我们需要锁定用户.对于这个问题,很多管理员会打开SL的Users窗口 ...

  8. 01_微信小程序支付

    [支付流程] 1.小程序内调用登录接口,获取到用户的openid(我们这一步骤让前端去获取) 2.服务端代码这边生成订单 3.服务端调用支付统一下单的api 4.服务端将再次签名,返回5个参数(前端得 ...

  9. 微信小程序开发2-第一个小程序开发准备

    1.首先在官网上注册一个账号( https://mp.weixin.qq.com/ )申请一个AppID(类似于人的身份证,小程序也需要身份证) 注册过程不多说 2.安装开发工具( https://m ...

  10. [英中双语] Pragmatic Software Development Tips 务实的软件开发提示

    Pragmatic Software Development Tips务实的软件开发提示 Care About Your Craft Why spend your life developing so ...