__init__中的类参数测试

时间:2012-07-12 11:15:55

标签: python exception

我有一个类Point,它接受​​位置,值和标志作为参数。此类应仅接受整数作为位置和值参数。我尝试了下面的代码,但它无法正常工作。

class PointException(Exception):
    pass

class Point():
    def __init__(self, position, value, flag=False):
        try:
            if all([isinstance(x, int) for x in position, value]):
                self.position = position
                self.value = value
                self.point = (position, value)
            self.flag = flag
        except:
            raise PointException("Foo value and position must be integers.")

    def __repr__(self):
        return "< {0}, {1}, {2} >".format(self.position, self.value, self.flag)

    def __eq__(self, other):
        if not isinstance(other, Point):
            return False
        try:
            return all([self.point == other.point, self.flag == other.flag])
        except AttributeError:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

更新

例如,当我尝试AttributError时,我得到Point(1, 1.2)

AttributeError: Point instance has no attribute 'position'

2 个答案:

答案 0 :(得分:3)

if all([isinstance(x, int) for x in position, value])

应该是

if all(isinstance(x, int) for x in (position, value))

更一般地说,您必须在raise__init__例外,而不是except

def __init__(self, position, value, flag=False):
    if not all(isinstance(x, int) for x in (position, value)):
        raise PointException("Foo value and position must be integers.")

    self.position = position
    self.value = value
    self.point = (position, value)
    self.flag = flag

您可以在其他答案中了解其他改进领域

答案 1 :(得分:2)

一般来说,你真的不想做这样的事情 - 你希望有责任使用正确的类型与实例化器,而不是类。

但是如果你确实想强制数字是整数,那么Python有一个特殊的模块:numbers

import numbers
isinstance(position, numbers.Integral) and isinstance(value, numbers.Integral)

或者,如果您必须使用all

all(isinstance(x, numbers.Integral) for x in (position, value))

不需要[]

相关问题