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)

转载于:https://www.cnblogs.com/sening/p/10283969.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值