python tips

巴扎黑
Release: 2016-12-09 13:27:14
Original
2494 people have browsed it

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
Copy after login



2. Check whether the string is a number

Python code

s='123456789'  
s.isdigit()#return True
Copy after login


3. List intersection

Python code

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


4. Two lists Convert to a dict

Python code

dict(zip(a,b))
Copy after login



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
Copy after login


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
Copy after login


6.list Duplication removal

Python code

{}.fromkeys(list).keys()
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template