Staticmethod is basically the same as a global function , except that it can be passed through the class or class instance object
(Python Li Guang says objects are always prone to confusion, because everything is objects, including classes, and actually
The class instance object is the one that corresponds to the so-called object in the static language , and is not implicitly passed in
Any parameters. This is more like static methods in static languages.
A Classmethod is a class-related method that can be called through classes or class instances .
The class object (not an instance object of Class) is implicitly passed in as the first parameter.
This approach may be a bit more odd, but as long as you figure out what Python is really
An object that exists in memory, not a type that exists only during compilation in a static language.
A normal method is a method associated with an instance object of a class that is called through a class instance object .
The instance object is implicitly passed in as the first parameter, which is also compared to other languages.
Examples can be as follows:
1 #!/usr/bin/python22.#Coding:utf-833. 44.#Author:gavingeng55.#date:2011-12-03 10:50:0166. 77.classPerson :88. 99.def __init__(self):Ten10.Print "Init" One11. A12. @Staticmethod -13.defSayHello (hello): -14.if notHello: thehello=.'Hello' -16.Print "I'll sya%s"%Hello -17. -18. +19. @Classmethod -20.defintroduce (clazz, hello): +21st. Clazz.sayhello (Hello) A22.Print "From introduce method" at23. -24.defHello (Self, hello): -25. Self.sayhello (Hello) -26.Print "From Hello method" -27. -28. in29.defMain (): -Person.sayhello ("haha") toPerson.introduce ("Hello world!") +32.#Person.hello ("Self.hello") #TypeError: Unbound method Hello () must be called with person instance as first argument (g OT str instance instead) -33. the34.Print "*"* 20 *p =Person () $P.sayhello ("haha") Panax NotoginsengPanax P.introduce ("Hello world!") -P.hello ("Self.hello") the39. +40.if __name__=='__main__': AA. Main ()
Output
1 I'll sya haha 2 2. I'll sya hello world! 3 3. From introduce method 4 4. ******************** 5 5 . Init 6 6. I'll sya haha 7 7. I'll sya hello world! 8 8. From introduce method 9 9. I'll sya Self.hello 10 10.from Hello Method
The difference between staticmethod Classmethod and normal functions in Python