zoukankan      html  css  js  c++  java
  • python的一些面试题(1)

    Python针对不可变对象的优化测试

    >>> a,b=(1,1) 
    >>> a is b
    True
    >>> a=1
    >>> b=1
    >>> a is b
    True
    >>> id(a)
    31957336
    >>> id(b)
    31957336
    >>> a=2
    >>> a is b
    False
    >>> a,b=1,1
    >>> a is b
    True
    >>> a,b="1","1"
    >>> a is b
    True
    >>> id(a)
    139747272688664
    >>> id(b)
    139747272688664
    

    超时装饰器的实现方式

    1.通过信号量实现,确定 只能在主线程中生效

    #-*- coding: utf-8 -*-
    import signal
    import traceback
    import time
    
    class RuntimeError(Exception):
        pass
    #信号量方法实现 超时  只能在主线程中生效
    def set_timeout(num, callback):
        def wrap(func):
            def handle(signum, frame):
                print "handle func {} {}".format(signum,frame)
                raise RuntimeError
                # raise
            def to_do(*args, **kwargs):
                try:
                    signal.signal(signal.SIGALRM, handle)  # 设置信号和回调函数
                    signal.alarm(num)  # 设置 num 秒的闹钟
                    print('start alarm signal.')
                    r = func(*args, **kwargs)
                    print('close alarm signal.')
                    signal.alarm(0)  # 关闭闹钟
                    return r
                except RuntimeError as e:
                    callback()
                except Exception as e:
                    print e,traceback.format_exc()
                    callback()
            return to_do
        return wrap
    if __name__ == '__main__':
        def after_timeout():
            print("函数超时")
    
        #用装饰器实现超时的信号量和线程实现
        @set_timeout(2,'thr', after_timeout)
        def connect():
            time.sleep(4)
            print('function run end')
        connect()
    

    2.线程方式的实现,使用daemon属性实现,问题会拉长主线程的运行时间,如果子线程已经结束,父线程还在傻傻的等待

    #-*- coding: utf-8 -*-
    from threading import Thread
    import time
    
    class RunTimeError(Exception):
        pass
    
    
    #这种方式当被装饰的函数运行完成之后 仍然会等待timer秒
    def time_out(timer):
        def waper(func):
            def __waper(*args):
                t = Thread(target=func,args = args)
                t.daemon = True
                t.start()
                time.sleep(timer)
                if t.is_alive():
                    raise RunTimeError('func run timeout')
            return __waper
        return waper
    
    parent = (2,23)
    @time_out(1)
    def test_thraed(*parent):
        print 'time out func parent {}'.format(parent)
        time.sleep(parent[0])
    
    test_thraed(*parent)
    

    3.通过join方式实现,我感觉挺好的 不过用到了线程的一个私有属性_Thread__stop

    #-*- coding: utf-8 -*-
    from threading import Thread
    import time
    
    class RunTimeError(Exception):
        pass
    ThreadStop = Thread._Thread__stop
    def time_out(timer):
        def waper(func):
            def __waper(*args):
                class MyThread(Thread):
                    def __init__(self):
                        Thread.__init__(self)
    
                    def run(self):
                        func(*args)
    
                    def _stop(self):
                        if self.is_alive():
                            ThreadStop(self)
                t = MyThread()
                t.start()
                t.join(timeout=timer)
                if t.is_alive():
                    t._stop()
                    raise RunTimeError("Func run Error {}".format(t.is_alive()))
            return __waper
        return waper
    parent = (2,23)
    @time_out(1)
    def test_thraed(*parent):
        print 'time out func parent {}'.format(parent)
        time.sleep(parent[0])
        print 1111111111111111111
    test_thraed(*parent)
    
  • 相关阅读:
    html 中 获取百度代码
    org.springframework.web.context.ContextLoaderListener
    短信验证
    云邦互联 免费空间申请
    linux 设置mysql 数据库编码utf8
    windows系统下简单nodejs安装及环境配置
    Oracle数据库创建表ID字段的自动递增
    芒果云 在线代码编辑器
    linux lanmp一件安装包
    linux下 安装php的gettext模块
  • 原文地址:https://www.cnblogs.com/sening/p/10283969.html
Copyright © 2011-2022 走看看