我有一個類Point
,它接受位置,值和標誌作爲參數。這個類只能接受整數作爲位置和值的參數。我嘗試了下面的代碼,但它不能正常工作。__init__中的類參數測試
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'
只有當傳遞的值是int時,點纔有屬性'position',否則if條件在'__init__'內失敗 – avasal 2012-07-12 11:24:24