pycharm 显示类方法的警告并在解决时产生错误

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

我正在编写一个错误处理程序类,Pycharm建议我的

method may be static
,我已经浏览了here,但是当我添加装饰器
@staticmethod
时,调用该对象会导致错误,并且它要求我提供一个
self 
输入。我总是这样写错误处理:

import os.path


class FileError(Exception):
    pass


class ColumnError(Exception):
    pass


class ChartError(Exception):
    pass


class ErrorHandler:
    def __init__(self):
        pass

    def handle_file_error(self, file_name):
        if not file_name:
            raise FileError("No file found")
        elif not file_name.endswith((".csv", ".xlsx", ".xls", ".json")):
            raise FileError("Wrong File, please upload a supported format, csv, excel or json")
        elif not os.path.exists(file_name):
            raise FileError("File does not exist")

    def chart_error(self, chart_type, available_charts):
        if chart_type not in available_charts:
            raise ChartError(f"{chart_type} not supported, please choose from: {', '.join(available_charts)}")

    def handle_column(self, df, column_name):
        if df is None or not hasattr(df, 'columns'):
            raise ColumnError("Could not show columns in the uploaded dataframe")
        if column_name not in df.columns:
            raise ColumnError("Column not available")


error_handler = ErrorHandler()
error_handler.handle_file_error("Budget.xlsx")`

请注意,此代码按我的预期工作,但我试图查看 pycharm 错误消息背后的原因,并可能避免将来的错误。

如果我遵循 pycharm 建议,它会将函数带出类,如下所示:

def handle_file_error(file_name):
    if not file_name:
        raise FileError("No file found")
    elif not file_name.endswith((".csv", ".xlsx", ".xls", ".json")):
        raise FileError("Wrong File, please upload a supported format, csv, excel or json")
    elif not os.path.exists(file_name):
        raise FileError("File does not exist")


class ErrorHandler:
    def __init__(self):
        pass

这违背了我在其他代码中调用此类的目的。

python error-handling pycharm
1个回答
0
投票

PyCharm 建议将方法设为静态时遇到的问题源于 Python 中实例方法和静态方法之间的差异。

请尝试这种方式,我认为这会引导您找到解决方案:

没有

@staticmethod:
(正如你最初写的)

class ErrorHandler:
    def handle_file_error(self, file_name):
        if not file_name:
            raise FileError("No file found")
        elif not file_name.endswith((".csv", ".xlsx", ".xls", ".json")):
            raise FileError("Wrong File, please upload a supported format, csv, excel or json")
        elif not os.path.exists(file_name):
            raise FileError("File does not exist")

error_handler = ErrorHandler()
error_handler.handle_file_error("Budget.xlsx")

@staticmethod:

class ErrorHandler:
    @staticmethod
    def handle_file_error(file_name):
        if not file_name:
            raise FileError("No file found")
        elif not file_name.endswith((".csv", ".xlsx", ".xls", ".json")):
            raise FileError("Wrong File, please upload a supported format, csv, excel or json")
        elif not os.path.exists(file_name):
            raise FileError("File does not exist")

ErrorHandler.handle_file_error("Budget.xlsx")
© www.soinside.com 2019 - 2024. All rights reserved.