Python class functions, instance functions, static functions

Source: Internet
Author: User
Tags class definition instance method

First, the realization method
classFunction (object):#defining variables in a class definitionCls_variable ="class Varibale"    def __init__(self):#to create a variable in a constructorSelf.__instance_variable="instance Variable"    defInstance_method (self):Print(self.cls_variable)Print(self.)__instance_variable)        Print("This is a instance method") @staticmethoddefStatic_method ():Print(function.cls_variable)#Print (function.__instance_variable) error here, unable to access instance variable        Print("This is a static method") @classmethoddefClass_method (CLS):Print(cls.cls_variable)#Print (cls.__instance_variable) error here, unable to access instance variable        Print("This is a class method") @classmethoddefset_class_variable (CLS): Cls.cls_variable='New class variable'    defSet_instace_varibale (self): self.__instance_variable='new instance Varibale'#class instances can call class methods and static methodsFunction1 =Function () function1.set_class_variable () Function1.class_method () Function1.instance_method () Function1.static_method () function2=Function () Function2.set_instace_varibale () Function2.class_method () Function2.instance_method () Function2.static_method ()


1. From the code definition, you can see that only the default incoming parameters are different.

Function.class_method () Function.static_method ( ) # You can call an instance function, but you need to pass in an instance variable Function.instance_method (function1)

2, from the code access, through the instance access to these three methods are the same. However, when class access is not the same, the instance function needs to pass in the instance.

3, the function accesses the variable, has the very big difference.

@classmethod     def Class_method (CLS):         Print (cls.cls_variable)         # print (cls.__instance_variable)   error here, unable to access instance variable

The init function defines an instance variable, because the variable prefix adds self. Class variables that are defined at the beginning of the class do not need to be prefixed.

In variable access, it is found that the class function and the static function cannot directly access the instance variable, because in subsequent calls, the instance is not known. However, instance functions can access class variables.

4. Modify the range of variables

 class is class class is class   is a static method

Is the result of the output in the function1.

 class is class class is class   isclass variable

This is the result of function2, and the class variable has changed.

If you modify a variable through a class method, the class variable in all instances is modified, like a static variable.

If the variable is modified by an instance, only the corresponding instance variable is modified.

Two, the three choice principle

Through the first section of the analysis, we learned that the three different, in access rights and methods, class methods and static methods have many similarities. The difference from an instance method is to see if the method is unique to the instance, or it needs to access the instance variable. The other difference is in the inheritance.

1. Class methods and Static methods
#-*-coding:utf-8-*-"""@Time: 2017/12/29 9:50@author:dongbl@description:"""classFunction (object): X= 1Y= 2@staticmethoddefAverag (*mixes):returnSUM (MIXES)/len (mixes) @staticmethoddefStatic_method ():#with a function call, if the class name is modified, it is not convenient to modify it here        returnFunction.averag (function.x, FUNCTION.Y) @classmethoddefClass_method (CLS):returnCls.averag (CLS. X, CLS. Y)classSubclass (Function): X=3Y= 5@staticmethoddefAverag (*mixes):returnSUM (mixes)/3func=Subclass ()Print(Func.static_method ())Print(Func.class_method ())

1, the calling method is different, on the other hand, if the class name is modified, the function also modifies

2, inheritance. This is the biggest difference between the two.

1.52.6666666666666665

Above is the output of both.

The instance of the subclass inherits the Static_method static method of the parent class, calls the method, or invokes the method and class properties of the parent class.
An instance of a subclass inherits the Class_method class method of the parent class, calls the method, calls the method of the subclass, and the class property of the child class.

This is the biggest difference, the static method in the class is not initialized, has been loaded, subsequent inheritance and she has no relationship. At the same time, the static method key clearly indicates the method that called the function, so it cannot be modified. This is the essence.

Third, class methods and Example methods

The most common method in a class is an instance method, that is, a method that passes an instance as the first parameter.

What if we wanted to write a few ways to interact with the class instead of interacting with the instance ? You can use the @Classmethod adorner to create a class method after Python2.2.

For example, we create a class:

class datetest ():     def __init__ (self,year,month,day):              = year        = day = Monthdef  print_date (self):                  Print ("{}:{}:{}". Format (self.year,self.month,self.day))

If the user enters a character like "2017-12-02", we need to adjust it before calling the class.

This design angle allows you to understand that each instance can invoke this conversion function.

#-*-coding:utf-8-*-"""@Time: 2017/12/29 9:50@author:dongbl@description:"""classdatetest ():def __init__(self,year,month,day): Self.year=Year Self.day=Day Self.month=Monthdefprint_date (self):Print("{}:{}:{}". Format (self.year,self.month,self.day)) @classmethoddefget_date (cls,string_date): Year,month,day= Map (Int,string_date.split ('-'))        returnCLS (year,month,day) T= Datetest (2017,9,10) R= Datetest.get_date ("2017-12-09") r.print_date () t.print_date ()

The main purpose of Classmethod is as a constructor function.
Python has only one constructor __new__, which is inconvenient if you want multiple constructors. You can only write a bunch of if isinstance in new.
With Classmethod, you can use Classmethod to write different constructors, such as:
Dict.fromkeys
Fractions. Fraction.from_decimal
Inspect. Signature.from_function
Most classmethod in Python end up with return CLS (XXX), return xxx.__new__ (), etc.

The main purpose of Staticmethod is to limit the namespace, that is, although this function is a normal functions, but it only this class will be used, not the function of the module level. This is the time to take it as a staticmethod.
If you do not consider the problem of namespace, directly inside the module def function is OK. Iv. Reference Documents


1, the Python class static method and the class method difference

2. Classic Solutions

Python class functions, instance functions, static functions

Related Article

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.