python @classmethod @staticmethod

 

@classmethod means:python

when this method is called, we pass the class as the first argument instead of the instance of that class. This means you can use the class and its properties inside that method rather than a particular instance.ide

@staticmethod means:this

when this method is called, we don't pass an instance of the class to it .This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance)..net

#!/usr/bin/python
#coding:utf-8

class Person:
    def __init__(self):
            print "init"

    @staticmethod
    def s_sayHello(hello):
        print "fun:s_sayhello %s" %hello
    @classmethod
    def c_introduce(clazz,hello):
        clazz.s_sayHello(hello)
    def hello(self,hello):
        self.s_sayHello(hello)   


def main():
    print "Person.s_sayHello:"
    Person.s_sayHello("Person:s_sayHello!")
    print "Person.c_introduce"
    Person.c_introduce("Person:c_introduce!");print "*"* 20;p=Person()
    p.s_sayHello("p:s_sayHello!")
    p.c_introduce("p:c_introduce!")
    p.hello("p:hello!")

if __name__=='__main__':
    main()
輸出
Person.s_sayHello:
fun:s_sayhello Person:s_sayHello!
Person.c_introduce
fun:s_sayhello Person:c_introduce!
********************
init
fun:s_sayhello p:s_sayHello!
fun:s_sayhello p:c_introduce!
fun:s_sayhello p:hello!
相關文章
相關標籤/搜索