如何使用装饰器,在类内部定义,没有警告

问题描述 投票:0回答:1

我在类中定义了装饰器并尝试在同一个类中使用它。
我已经根据 this 主题创建了装饰器。但 PyCharm 告诉我,这是一种非常好的方法。
这是代码:

import sys
from typing import Callable


class TestClass:
    def __init__(self):
        self.smile = ':P'

    def handle_exception(func: Callable):
        def handle_exception_wrapper(self=None, *args, **kwargs):
            try:
                func(self, *args, **kwargs)
                return self.shutdown()
            except Exception as error:
                self.shutdown(error)

        return handle_exception_wrapper

    @handle_exception
    def some_function(self) -> None:
        print('some suspicious function is working')
        raise RuntimeError('Break Runtime - all be fine')
    
    def shutdown(error=None):
        if error:
            print('error:', error)
            print('function collapsed')
        else:
            print('good-boy function completed the task')
        print('goodbye', self.smile)
        sys.exit(1)

    


test = TestClass()
test.some_function()

以及 IDE 警告:

这段代码可以工作(装饰器悄悄地传递一个类对象)。但看起来有点sus和“inPEPful”。

长话短说,是否可以在类中漂亮地定义和使用装饰器? (一件事很重要,我想访问装饰器内的类方法)。

python python-3.x exception decorator
1个回答
0
投票

我不会自信地告诉你这会达到你想要的效果,但你可以通过将

handle_exception
设置为静态方法,并在
self
中添加
shutdown
参数并在末尾添加换行符来修复 PyCharm 错误。这是文件,PyCharm 无警告版本:

import sys
from typing import Callable


class TestClass:
    def __init__(self):
        self.smile = ':P'

    @staticmethod
    def handle_exception(func: Callable):
        def handle_exception_wrapper(self, *args, **kwargs):
            try:
                func(self, *args, **kwargs)
                return self.shutdown()
            except Exception as error:
                self.shutdown(error)

        return handle_exception_wrapper

    @handle_exception
    def some_function(self) -> None:
        print('some suspicious function is working')
        raise RuntimeError('Break Runtime - all be fine')

    def shutdown(self, error=None):
        if error:
            print('error:', error)
            print('function collapsed')
        else:
            print('good-boy function completed the task')
        print('goodbye', self.smile)
        sys.exit(1)


test = TestClass()
test.some_function()

在 PyCharm 2023.3.4 社区版、Windows 11 上的 Python 3.11.7 上进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.