Staticmethod and Classmethod in Python

Source: Internet
Author: User
Tags class definition instance method python decorator

Original Address 68957848

Original Address 78165645

Original Address https://www.cnblogs.com/1204guo/p/7832167.html

In Python, the methods defined in class can be broadly divided into three categories: instance methods, class methods, and static methods.

Use a table to summarize the following:

Method Type Retouching called by Default first parameter
Instance method No Instance Self
Class method @classmethod CLS, instance Cls
Static methods @staticmethod CLS, instance No

Example:

classFoo ():#No modification    defInstance_method (self):#The first parameter passed in is self, which is the instance itself        Print('The first argument of Instance_method:', self) @classmethoddefClass_method (CLS):#The first parameter passed in is class        Print('The first argument of Class_method:', CLS) @staticmethoddefStatic_method ():#There is no default first parameter, only custom parameters        Print('The first argument of Static_method:') Foo=Foo () Foo.instance_method () Foo.class_method () Foo.class_method () Foo.static_method () Foo.static_method () Try: Foo.instance_method ()except:    Print('instance method can not be accessed through class.')

Output:

The first argument of Instance_method: <__main__. Foo object at 0x7fd135ec3b38><class'__main__. Foo'><class'__main__. Foo'>notclass

Need to note:
1. @classmethod with the @staticmethod built-in methods that is Python.
2. The special method __new__ , although not @classmethod decorated, is also a class method.

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

Classmethod: Class method
Staticmethod: Static method

In Python, both static and class methods can be accessed through class objects and class object instances. But the difference is:

@classmethod is a function modifier, which means that next is a class method, which is called an instance method for what we usually see. The first parameter of the class method is CLS, and the first argument of the instance method is self, which represents an instance of the class.

A normal object method requires at least one self parameter, which represents the Class object instance

Class methods have the class variable CLS incoming, so that some related processing can be done with the CLS. and with subclass inheritance, when the class method is called, the passed-in class variable CLS is a subclass, not a parent class.

For a class method, it can be called through a class, like C.F (), a bit like a static method in C + +, or it can be called through an instance of the class, like C (). f (), here C (), written so that it is an instance of the class.

Static method is not, it is basically the same as a global function, generally used very little

Classmethod must use a class object as the first argument, and Staticmethod can pass no arguments.

classDate:def __init__(Self,day=0, Month=0, year=0): Self.day=Day Self.month=month Self.year=Year @classmethoddeffrom_string (CLS, date_as_string): Day, month, year= Map (Int,date_as_string.split ('-')) My_date=CLS (Day, month, year)returnmy_date @staticmethoddefIs_date_valid (date_as_string): Day, month, year= Map (int, date_as_string.split ('-'))        returnDay <= 31 andMonth <= 12 andYear <= 3999if __name__=='__main__': My_date= Date.from_string ('11-09-2012')    Print(My_date.day, my_date.month,my_date.year) is_date= Date.is_date_valid ('13-13-2012')    Print(is_date) outputs:11 9 2012False

Looking at another example, in order to verify that a subclass inherits, when a subclass calls that class method, the passed-in class variable CLS is a subclass, not a parent class

classA: @classmethoddefcm (CLS):Print('class method cm (CLS) Caller:'Cls.__name__) @staticmethoddefSM ():Print('static method SM () is called')classB (A):Passa.cm ()#class method cm (CLS) Caller: AB.CM ()#class method cm (CLS) Caller: BA.sm ()#static method SM () is calledB.sm ()#static method SM () is called

Let's see why we need to use Staticmethod and Classmethod.

class Kls:     def __init__ (self,data):         = Data    def  printd (self):        print(self.data) ik1=kls ( ' Arun ' ) ik2=kls ('Seema') ik1.printd () Ik2.printd ()
#What if we wanted to write a few ways to just interact with the class instead of interacting with the instance? We can write an easy way out of the class to do this,#but doing so spreads out the class code's relationship to the outside of the class definition. If you write like this, it can cause difficulties in future code maintenance:defget_no_of_instances (cls_obj):returnCls_obj.no_instclassKls:no_inst=0def __init__(self): Kls.no_inst= Kls.no_inst + 1Ik1=Kls () ik2=Kls ()Print(Get_no_of_instances (Kls))#2

Application Classmethod

classKls (object): No_inst=0def __init__(self): Kls.no_inst= Kls.no_inst + 1@classmethoddefget_no_of_instance (cls_obj):returnCls_obj.no_instik1=Kls () ik2=Kls ()Print(Ik1.get_no_of_instance ())Print(Kls.get_no_of_instance ())#2#2

@staticmethod
There are often functions that are related to the class, but static methods are required when the runtime does not require instances and classes to participate.

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

There are 3 main methods of Python, namely static methods (Staticmethod), class methods (Classmethod), and instance methods, as follows:

12345678910111213141516 deffoo(x):    print "executing foo(%s)"%(x) classA(object):    deffoo(self,x):        print "executing foo(%s,%s)"%(self,x)     @classmethod    defclass_foo(cls,x):        print "executing class_foo(%s,%s)"%(cls,x)     @staticmethod    defstatic_foo(x):        print"executing static_foo(%s)"%x a=A()

The self and the CLS are bindings to classes or instances, which we can call for general functions, which are foo(x) most commonly used, and whose work has nothing to do with anything (classes, instances). For instance methods, we know that we need to bind this instance every time we define a method in a class, that is foo(self, x), why do you do this? Because the invocation of the instance method is inseparable from the instance, we need to pass the instance to the function, which is a.foo(x) called when (In fact foo(a, x) ). class method, except that it passes a class instead of an instance A.class_foo(x) . Note that the self and the CLS here can replace the other parameters, but the Python convention is these two, or do not change the good.

For static methods, like normal methods, there is no need to bind to who, the only difference is that the call needs to be used a.static_foo(x) or A.static_foo(x) called.

Staticmethod and Classmethod in Python

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.