python - 属性错误: can't set attribute - Python instance attribute assignment

标签 python

我遇到了一个与实例属性相关的奇怪问题。我有一个变量logger,我想将其作为实例属性。但是,我收到错误 AttributeError: can't set attribute unless 我将属性 logger 移到 __init__() 函数,这(IIRC)意味着我将 logger 声明为类属性(不是我想要的)。

这是我的代码片段:

class MyScraper(ABC,scrapy.Spider):
    """Abstract base class for scraping non JS Web pages"""
    #logger = None    # Commented out, as I don't want class instance

    def __init__(self, *args, **kwargs): 
        self.connection = None
        self.channel = None
        self.topic = None            

        log_format = "%(asctime)s - %(levelname)s - %(message)s"
        log_level = 10
        handler = TimedRotatingFileHandler("{0}.log".format(kwargs['log_filename']), when="midnight", interval=1)
        handler.setLevel(log_level)
        formatter = logging.Formatter(log_format)
        handler.setFormatter(formatter)

        # add a suffix which you want
        handler.suffix = "%Y%m%d"

        #need to change the extMatch variable to match the suffix for it
        handler.extMatch = re.compile(r"^\d{8}$") 

        self.logger = logging.getLogger('my_logger') # <- barfs here

        # finally add handler to logger    
        self.logger.addHandler(handler)   

        # Set up messaging infrastructure ...

为什么我会收到此错误,以及如何修复它?

最佳答案

如果你看source code (或者即使您只是 print(scrapy.Spider.logger) 您也可以看到 Spider.loggerproperty ,特别是没有定义 setter,所以你不能轻易地分配给它。

如果您想添加其他处理程序,则不一定需要创建自己的记录器,因此我不确定除此之外您还想实现什么目标。不过,如果您“真的”想要覆盖默认的 self.logger,由于您是 Spider 的子类,因此没有什么可以阻止您添加以下内容:

@property
def logger(self):
    return logging.getLogger('my_logger')

到你的类(class)。

关于python - 属性错误: can't set attribute - Python instance attribute assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46829930/

相关文章:

python - 尝试在 python 中的文件对象上调用 readline() 但它正在暂停

python - os.rename() 移动目录但不删除旧目录。它就像复制一样

python - 如何清理正则表达式

python - 是否可以在 scikit-learn 中使用自定义内核的网格搜索来调整参数?

python - 从一个数据框中获取缺失的列并将其附加到另一个数据框中

Python 3.6 Split() 没有足够的值来解压解决方法?

python - .matplotlibrc 和默认选项

python - 如何将无序文件夹迁移到 Plone 中的有序文件夹

python - 如何使用 djongo 作为数据库后端在 django 中进行 mongodb ACID 事务?

python - 广播 NumPy 数组时实际发生了什么