【问题标题】:iadd in python classpython类中的iadd
【发布时间】:2015-11-17 22:31:47
【问题描述】:

我创建了一个类并改进了 add 函数,但由于某种原因它无法正常工作。这就是我所拥有的:

def __iadd__(self,thing): 

    try: 
        tester=True
        for y in thing:
            if type(y) != type('f'):
                tester=False
        for j in thing:
            self.listt.append(j)
        return self
    except(tester==False):
        return ValueError

每当我这样做时:

f=class('ab')

f += [4]   

它应该返回一个ValueError,因为我正在添加一些不是字符串的东西,但由于某种原因它正在附加 int,即使它也不应该也是如此。

【问题讨论】:

  • 您使用的 try/except 块错误。如果你想让它进入except块,你需要raise一个错误
  • 如果您提出异常,所有except(tester==False): 会给您一个catching classes that do not inherit from BaseException is not allowed

标签: python class add


【解决方案1】:
def __iadd__(self, thing): 
    for y in thing:
        if not isinstance(y, str):
            raise ValueError
    for j in thing:
        self.listt.append(j)
    return self

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2021-08-09
    • 2021-09-08
    • 2013-09-24
    • 2021-02-13
    • 2011-04-22
    • 1970-01-01
    相关资源
    最近更新 更多