首页 > 解决方案 > 我有一个具有一个必需参数和两个可选参数的类,以及一个返回可选参数之一的 repr 方法,以给定者为准

问题描述

class MyClass():
    def __init__(self, name, high=None, low=None):
        self.name = name
        if low:
            self.low = low
        elif high:
            self.high = high
        else:
            raise Error("Not found")

    def __repr__(self):
        value = self.low or self.high
        return '{}({}, {})'.format(str(self), self.name, value)

我有一个单元测试用例,其中 MyClass 被实例化,

gain = MyClass('name', high='high_value')
assert isinstance(repr(gain), str)

但是当我的 repr() 被调用时,它会抛出 AttributeError,

AttributeError:“MyClass”没有属性“低”

标签: pythonreprisinstance

解决方案


我会将您的代码重构为以下内容

class MyClass:
    def __init__(self, name, high=None, low=None):
        self.name = name
        self.low = low
        self.high = high
        if self.low is None and self.high is None:
            raise Error("Not found")
        if self.low is not None and self.high is not None:
            raise Error("Only low OR high may be specified, not both")
        
    def __repr__(self):
        value = self.low if self.low is not None else self.high
        return '{}({}, {})'.format(str(self), self.name, value)

因此,在__init__您的断言中,恰好设置了低或高之一,换句话说,既没有设置也没有设置两者都是错误的。然后,您可以根据传入的值__repr__进行分配。在这种情况下,和都将存在,尽管它们的值之一是.valueself.lowself.highNone


推荐阅读