zoukankan      html  css  js  c++  java
  • python的cls,self,classmethod,staticmethod

    原文链接:http://blog.csdn.net/xluren/article/details/9168535#

    Python类里会出现这三个单词,self和cls都可以用别的单词代替,类的方法有三种,

    一是通过def定义的 普通的一般的,需要至少传递一个参数,一般用self,这样的方法必须通过一个类的实例去访问,类似于c++中通过对象去访问;

    二是在def前面加上@classmethod,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用;

    三是在def前面加上@staticmethod,这种类方法是静态的类方法,类似于c++的静态函数,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式;

    1. class A:  
    2.     member = "this is a test."  
    3.     def __init__(self):  
    4.         pass  
    5.  
    6.     @classmethod  
    7.     def Print1(cls):  
    8.         print "print 1: ", cls.member  
    9.           
    10.     def Print2(self):  
    11.         print "print 2: ", self.member  
    12.             
    13.          
    14.     @classmethod      
    15.     def Print3(paraTest):  
    16.         print "print 3: ", paraTest.member  
    17.     @staticmethod  
    18.     def print4():  
    19.         print "hello"  
    20.       
    21.   
    22. a = A()  
    23. A.Print1()    
    24. a.Print1()  
    25. #A.Print2()  
    26. a.Print2()  
    27. A.Print3()  
    28. a.Print3()   
    29. A.print4()  
  • 相关阅读:
    OSCache报错error while trying to flush writer
    html 输入框验证
    Struts2 一张图片引发的bug
    Html 小插件10 即时新闻
    String
    内部类
    多态
    抽象&接口
    继承
    封装
  • 原文地址:https://www.cnblogs.com/canfengyiyue/p/7305379.html
Copyright © 2011-2022 走看看