Differences between staticmethod and classmethod in Python

Source: Internet
Author: User

Differences between staticmethod and classmethod in Python

Class MethodTest ():
Var1 = "class var"

Def _ init _ (self, var2 = "object var "):
Self. var2 = var2

@ Staticmethod

DefstaticFun ():
Print 'static Method'

@ Classmethod

DefclassFun (cls ):
Print 'class Method'

The similarities between staticmethod and classmethod are as follows:

1. Both can be called by class or instance

Mt = MethodTest ()

MethodTest. staticFun ()

Mt. staticFun ()

MethodTest. classFun ()

Mt. classFun ()

2. You cannot access instance members.

@ Staticmethod

DefstaticFun ():
PrintVar2 // Wrong
@ Classmethod

DefclassFun (cls ):
Print var2// Wrong

Differences between staticmethod and classmethod:

1. staticmethod requires no parameters. classmethod requires class variables to be passed as parameters (not class instances)

DefclassFun (cls ):
Print 'class Method'// Pass cls as class variables

2. classmethod can be a member of the callback class, but not a member of the staticmethod class.

@ Staticmethod

DefstaticFun ():
PrintVar1 // Wrong
@ Classmethod

DefclassFun (cls ):
Print cls. var1// Right

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.