python tips

巴扎黑
巴扎黑Original
2016-12-09 13:27:142563browse

1. enum

Python code

#!/usr/bin/env python  
# -*- coding:utf-8 -*-  
  
def enum(**enums):  
    return type('Enum', (), enums)  
Gender = enum(MALE=0,FEMALE=1)  
print Gender.MALE  
print Gender.FEMALE



2. Check whether the string is a number

Python code

s='123456789'  
s.isdigit()#return True


3. List intersection

Python code

s=[1,2,3]  
w=[2,3,4]  
list(set(s).intersection(w))


4. Two lists Convert to a dict

Python code

dict(zip(a,b))



5, singleton

Python code

def singleton(cls):  
    instances = {}  
    def get_instance():  
        if cls not in instances:  
            instances[cls] = cls()  
        return instances[cls]  
    return get_instance


The second singleton mode used in tornado IOLoop:

Python code

@staticmethod  
def instance():  
    """Returns a global IOLoop instance. 
 
    Most single-threaded applications have a single, global IOLoop. 
    Use this method instead of passing around IOLoop instances 
    throughout your code. 
 
    A common pattern for classes that depend on IOLoops is to use 
    a default argument to enable programs with multiple IOLoops 
    but not require the argument for simpler applications:: 
 
        class MyClass(object): 
            def __init__(self, io_loop=None): 
                self.io_loop = io_loop or IOLoop.instance() 
    """  
    if not hasattr(IOLoop, "_instance"):  
        with IOLoop._instance_lock:  
            if not hasattr(IOLoop, "_instance"):  
                # New instance after double check  
                IOLoop._instance = IOLoop()  
    return IOLoop._instance


6.list Duplication removal

Python code

{}.fromkeys(list).keys()


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:redis-pythonNext article:redis-python