在__init__中引发非int参数的异常

时间:2016-11-01 05:29:58

标签: python exception

我想实现类chmod a+r /etc/udev/rules.d/51-android.rules,这样当我传递非整数时,会引发异常并且不会创建对象。以下代码引发了异常,但可以创建一个奇怪的分数Fraction

'hello, world'/0

问题是,我如何优雅地捕获非整数输入和0分母?

更新 完全忘了我需要引发异常,而不仅仅是make class Fraction: def __init__(self, num, den): try: num = int(num) den = int(den) except ValueError: print('Passed argument not convertible to int') self.num = num self.den = den 子句。这是代码现在的样子

except

4 个答案:

答案 0 :(得分:0)

except块中只有raise原始异常。 要检查零分母,请执行以下操作:

if den == 0:
    raise ValueError("boom")

答案 1 :(得分:-1)

您可以使用工厂方法创建对象:

class Fraction:
    def __init__(self, num, den):
        self.num = num
        self.den = den

def new_fraction(num, den):
    try:
        num = int(num)
        den = int(den)
        return Fraction(num, int)
    except ValueError:
        print('Passed argument not convertible to int')

然后当你想要一个新的Fraction调用工厂方法时:

my_fraction = new_fraction(1,5)

然后,您需要测试my_fraction是否为None:

if my_fraction is not None:
    # Do stuff
else:
    # my_fraction is not an instance of Fraction, so do something else

答案 2 :(得分:-1)

如果要打印或记录错误消息并引发异常,只需将raise添加到现有的除外套件中 - 它将引发最新的异常。使用描述符拒绝零分母。 NonZero改编自Python Descripters Demystified

import weakref

class NonZero(object):
    """A descriptor that forbids zero values"""
    def __init__(self, default):
        self.default = default
        self.data = weakref.WeakKeyDictionary()

    def __get__(self, instance, owner):
        # we get here when someone calls x.d, and d is a NonNegative instance
        # instance = x
        # owner = type(x)
        return self.data.get(instance, self.default)

    def __set__(self, instance, value):
        # we get here when someone calls x.d = val, and d is a NonNegative instance
        # instance = x
        # value = val
        if value == 0:
            raise ValueError("Denominator can not be zero")
        self.data[instance] = value


class Fraction:

    den = NonZero(1)

    def __init__(self, num, den):
        try:
            num = int(num)
            den = int(den)
        except ValueError as e:
            print('Passed argument not convertible to int')
            raise
        self.num = num
        self.den = den

对于后人,我的第一个解决方案是使用assert拒绝分母的零值,因此@ PM2Ring的评论。我和自己就使用它进行了辩论。它是文档状态:Assert statements are a convenient way to insert debugging assertions into a program - 并且位于UsingAssertionsEffectively的底部:Assertions should *not* be used to test for failure cases that can occur because of bad user input - 所以我很糟糕。描述符是要走的路。 (但断言肯定很方便)。

答案 3 :(得分:-1)

您的代码中的某个位置会调用

my_fraction = Fraction(num, den)

为什么不将其更改为:

if type(num) is int and type(den) is int:
  my_fraction = Fraction(num, den)
else:
  print('Passed argument not convertible to int')

这样就永远不会创建对象。如果需要,您还可以添加例外。