Python:检查属性是否存在时的AttributeError

Ore*_*reo -2 python attributeerror

我有一个日志类,允许将前缀添加到日志中.如果没有给出前缀,则默认为"".

class PrefixedLog(Loggable):
    def __init__(self):
        self._prefix = None

    @property
    def prefix(self):
        if self._prefix:
            return self._prefix
        else:
            return ""

    @prefix.setter
    def prefix(self, value):
        self._prefix = value

    @property
    def log(self):
        if not hasattr(self, '_log') or not self._log:
            log = logging.getLogger(self.__class__.__name__)
            self._log = LoggerAdapter(self._prefix, log)
        return self._log
Run Code Online (Sandbox Code Playgroud)

我有另一个类,然后创建另一个类的对象,我正在尝试设置前缀:

class A(PrefixedLog):
    def __init__(self, **kwargs):
        super(A, self).__init__(**kwargs)
        self.b = B()
Run Code Online (Sandbox Code Playgroud)

带前缀的类:

class B(PrefixedLog):
    self.another_class = AnotherClass()
    if self.prefix:
        self.another_class.prefix = 'desired prefix'
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

AttributeError: 'B' object has no attribute '_prefix'
Run Code Online (Sandbox Code Playgroud)

在...上

if self.prefix: 
Run Code Online (Sandbox Code Playgroud)

线.

我已经搜索了解决方案,但大多数都与格式问题有关...我已经确定没有标签.关于问题可能是什么的任何想法?提前致谢.

另外 - 我想确保即使一个类没有专门设置前缀,那么前缀默认为""没有任何错误,即我不必回到我拥有的每个类并设置前缀.

Jus*_*nan 5

你的意思是把代码放在方法的类B__init__()吗?我想这段代码:

class B(PrefixedLog):
    self.another_class = AnotherClass()
    if self.prefix:
        self.another_class.prefix = 'desired prefix'
Run Code Online (Sandbox Code Playgroud)

应改为:

class B(PrefixedLog):
    def __init__(self):
        super().__init__()
        self.another_class = AnotherClass()
        if self.prefix:
            self.another_class.prefix = 'desired prefix'
Run Code Online (Sandbox Code Playgroud)

  • 在检查`self.prefix`之前,你仍然需要调用`super()`. (2认同)