Python instance methods, class methods, and Static methods

Source: Internet
Author: User

A normal method, the first parameter needs to be self, which represents a specific instance of itself.
If you use Staticmethod, you can ignore this self and use this method as a normal function.
For Classmethod, its first argument is not self, which is the CLS, which represents the class itself.
>>> class A (object):
def test1 (self):
Print "Hello", self
@staticmethod
Def test2 ():
print "Hello"
@classmethod
def test3 (CLS):
Print "Hello", CLS


>>> a = A ()
>>> A.test1 () #最常见的调用方式, but the same way as below
Hello <__main__. A Object at 0x9f6abec>
>>> A.test1 (A) #这里传入实例a, equivalent to the normal method of self
Hello <__main__. A Object at 0x9f6abec>
>>> A.test2 () #这里, because there are no parameters to the static method, it is possible to pass things
Hello
>>> a.test3 () #这里, because it is a class method, its first argument is the class itself.
Hello <class ' __main__. A ' >
>>> a #可以看到, enter a directly, and return the same information as the above call.
<class ' __main__. A ' >

Python instance methods, class methods, and Static methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.