This is the third day of my participation in the August Text Challenge.More challenges in August

introduce

The Python language has a number of built-in functions that put soul into code, also known as “syntactic sugar”. Today is about using built-in decorators@staticmethod,@classmethodTheir main purpose is to encapsulate class methods as ordinary functions, as illustrated below.

@staticMethod How to use a static decorator

The following is encapsulated in class Chandel_array()Function. The idea of using a static decorator is to convert such methods into functions. Call againhandle_array()Function, without instantiating the class, can be directly called.

In normal functions, there is no need to pass in the self keyword syntax.

class C(object) : 
     def __init__(self, word) : 
         self.word = word

     @staticmethod
     def handle_array() : 
         print(['a'] * 10) 

     def get_word(self) : 
         print(self.word) 

C.handle_array() 
Copy the code

@classMethod How to use a class decorator

In this case, inDemoViewThere are two packages in@classmethodClass decorator, whose main function is to convert the method to a class function@staticmethodStatic decorator, class decorator functions that can call other methods in a class, and can also call methods in a parent class by inheritance.

In the following example,DemoviewIn the classdemo1_post()Class function, then calls the parent class method_post().

Class decorator that can be called directlyDemoView.demo1_post()Without instantiation. because@classmethodThe class decorator has converted the class method into a function, so it can be called directly.

class ConnectServer(object) : 
     """ Requests Connection Pool "" 
     def __init__(self) : 
         self.ip='127.0.0.1' 
         self.port='80' 

     def _post(self, *args, **kwargs) : 
         try: 
             response = requests.post( 
                 'http://' + self.ip + ':' + self.port + kwargs['url'], 
                 data=kwargs['data'], 
                 headers={'Content-Type': 'application/x-www-form-urlencoded'})return json.loads(response.text) 
         except Exception as e: 
             return {'code': 30000.'message': 'Connection %s server network unreachable' % self.ip, 'except': str(e)} 


class DemoView(ConnectServer) : 
     """Demo1""" 
     @classmethod
     def demo1_post(cls) : 
         # request data send
         response = cls()._post(url='/api/demo1', data='data') 
         return response

     @classmethod
     def demo2_post(cls) : 
         # request data send
         response = cls()._post(url='/api/demo2', data='data') 
         return response


DemoView.demo1_post() 
Copy the code

Summary, use@staticmethod,@classmethodEncapsulation, make the code logical processing more clear, reduce code redundancy. More Python features are coming. Please pay more attention to ~~