2

我有一个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'
4

2 回答 2

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

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

于 2012-07-12T11:19:41.500 回答
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))

没有必要[]

于 2012-07-12T11:23:49.560 回答