zoukankan      html  css  js  c++  java
  • python中staticmethod classmethod及普通函数的区别

    staticmethod 基本上和一个全局函数差不多,只不过可以通过类的实例对象

    (python里光说对象总是容易产生混淆, 因为什么都是对象,包括类,而实际上

    类实例对象才是对应静态语言中所谓对象的东西)来调用而已, 不会隐式地传入

    任何参数。这个和静态语言中的静态方法比较像。

    classmethod 是和一个class相关的方法,可以通过类实例调用,

    并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入。

    就这种方法可能会比较奇怪一点,不过只要你搞清楚了python里class也是个真实地

    存在于内存中的对象,而不是静态语言中只存在于编译期间的类型

    正常的方法 就是和一个类的实例对象相关的方法,通过类实例对象进行调用,

    并将该实例对象隐式地作为第一个参数传入,这个也和其它语言比较像。

    可如下示例:

     1 #!/usr/bin/python  
     2 2.#coding:utf-8  
     3 3.  
     4 4.#author:    gavingeng  
     5 5.#date:      2011-12-03 10:50:01   
     6 6.  
     7 7.class Person:  
     8 8.  
     9 9.    def __init__(self):  
    10 10.        print "init"  
    11 11. 
    12 12.    @staticmethod  
    13 13.    def sayHello(hello):  
    14 14.        if not hello:  
    15 15.            hello='hello'  
    16 16.        print "i will sya %s" %hello  
    17 17. 
    18 18. 
    19 19.    @classmethod  
    20 20.    def introduce(clazz,hello):  
    21 21.        clazz.sayHello(hello)  
    22 22.        print "from introduce method"  
    23 23.  
    24 24.    def hello(self,hello):  
    25 25.        self.sayHello(hello)  
    26 26.        print "from hello method"         
    27 27.  
    28 28.  
    29 29.def main():  
    30 30.    Person.sayHello("haha")  
    31 31.    Person.introduce("hello world!")  
    32 32.    #Person.hello("self.hello") #TypeError: unbound method hello() must be called with Person instance as first argument (got str instance instead)  
    33 33.      
    34 34.    print "*" * 20  
    35 35.    p = Person()  
    36 36.    p.sayHello("haha")  
    37 37.    p.introduce("hello world!")  
    38 38.    p.hello("self.hello")  
    39 39.  
    40 40.if __name__=='__main__':  
    41 41.    main()  

    output:

     1 i will sya haha  
     2 2.i will sya hello world!  
     3 3.from introduce method  
     4 4.********************  
     5 5.init  
     6 6.i will sya haha  
     7 7.i will sya hello world!  
     8 8.from introduce method  
     9 9.i will sya self.hello  
    10 10.from hello method  
  • 相关阅读:
    Leecode刷题之旅-C语言/python-383赎金信
    Leecode刷题之旅-C语言/python-349两整数之和
    Cesium 实现粒子效果贴地(伪)
    CesiumJS 添加会动的GIF
    sleep 和 wait 区别
    Git常用命令
    java 泛型
    java 设计模式 ---- 单例模式
    java 设计模式 ---- 工场模式
    java 线程池 ---- newCachedThreadPool()
  • 原文地址:https://www.cnblogs.com/chuanheng/p/python_staticmethod.html
Copyright © 2011-2022 走看看