I have a class Point that accepts position, value and flag as arguments. This class should accept only integers as position and value arguments. I tried the code below, but it doesn’t work properly.
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)
Update
I get an AttributError when I try Point(1, 1.2), for instance.
AttributeError: Point instance has no attribute 'position'
should be
And more generally you have to
raisethe exception in__init__, not catch it withexcept:There are other areas of improvement that you can read about in the other answers