2012-07-12 29 views
2

我有一個類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' 
+0

只有當傳遞的值是int時,點纔有屬性'position',否則if條件在'__init__'內失敗 – avasal 2012-07-12 11:24:24

回答

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 

有好轉等領域你可以在其他答案中閱讀

+0

沒有方括號。 – katrielalex 2012-07-12 11:20:24

+0

請注意,由於longs的緣故,這在Python 2中不會總是有效(你需要'isinstance(x,(int,long))'.BTW:'throw' /'catch'?我認爲有人一直在使用其他的language .. ;-) – DSM 2012-07-12 11:29:01

+0

'from __future__ import java_syntax' ;-) – 2012-07-12 11:31:47

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)) 

沒有必要爲[]