账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    类装饰器装饰类方法,对应的变量怎么传递
    43
    0
    import multiprocessing
    
    class Timeout(object):
        def __init__(self, timeout=60, max_retry=1):
            self.timeout = timeout
            self.max_retry = max_retry
    
        def __call__(self, original_func):
            decorator_self = self
    
            def wrapper(self,*args, **kwargs):
                count = decorator_self.max_retry
                q = multiprocessing.Queue()
                q.put(None)
    
    
                def __run(args, kwargs):
                    result = original_func(self,*args, **kwargs)
                    q.get()
                    q.put(result)
                    print(self.__dict__)
                    # original_func.__dict__['new']=2
    
                while count > 0:
                    job = multiprocessing.Process(target=__run, args=(args, kwargs))
                    job.start()
                    job.join(decorator_self.timeout)
                    if job.is_alive():
                        job.terminate()
                        count -= 1
                        continue
                    return q.get()
                return 'Timeout'
            return wrapper
    
    
    import time
    class P:
        def __init__(self):
            self.new=1
    
        @Timeout(2)
        def sleep(self):
            time.sleep(1)
            self.new=12
    
        def out(self):
            print(self.sleep())
            print(self.new)
    
    P().out()

    以上,在P中,如果不是用修饰器,out的print(self.new)会打印2,sleep方法上使用Timeout修饰器,打印的就是1,明显不是我想要的,我在Timeout里面能打印出P的__dict__有{'new':2},为什么没传出来,怎么让P的new能够正确接受2这个值,谢谢

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 喵了个咪。 普通会员 1楼

      在Python中,装饰器是一种特殊类型的函数,它可以接收另一个函数作为参数,并在其定义之前和之后添加额外的代码。装饰器通常用于增加函数的功能,或者在函数被调用之前和之后做一些额外的事情。

      如果你想要在装饰器中传递变量,你可以这样做:

      ```python def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") result = func() print("Something is happening after the function is called.") return result return wrapper

      @my_decorator def say_hello(): print("Hello!")

      say_hello() ```

      在这个例子中,my_decorator是一个装饰器,它接收一个函数func作为参数。然后,它定义了一个新的函数wrapper,在这个函数中,它在函数调用之前和之后打印了一些消息。最后,它返回wrapper函数。

      @my_decorator是一个装饰器语法糖,它告诉Python将my_decorator函数应用到say_hello函数上。所以,当我们调用say_hello函数时,实际上是在调用wrapper函数。

      所以,say_hello函数在调用之前和之后都会打印一些消息。这些消息是由my_decorator函数在其定义之前和之后添加的。

    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部