2016-05-09 6 views
-1

クラスのメソッドのパラメータが整数ではないのに、失敗した場合にTypeErrorを発生させたいと思います。コードは次のようになります。最初のパラメータに "N"を入れ、TypeErrorを取得し、 "Rectangleを非整数値に設定できません"という印刷が行われますが、代わりに "Traceback (最新の呼び出しの最後): ファイルが r1.setDataで "/Users/Janet/Documents/module6.py"、19行、(Nは、5) NameError:名前が 'N'Python3:TypeErrorを呼び出すことができません

class Rectangle: 
    def __init__ (self): 
     self.height = 0 
     self.width = 0 

    def setData(self, height, width): 
     if type(height) != int or type(width) != int: 
     raise TypeError() 
     if height <0 or width <0: 
     raise ValueError() 
     self.height = height 
     self.width = width 

    def __str__(self): 
     return "height = %i, and width = %i" % (self.height, self.width) 

r1 = Rectangle() 
try: 
    r1.setData(N,5) 
except ValueError: 
    print ("can't set the Rectangle to a negative number") 
except TypeError: 
    print ("can't set the Rectangle to a non-integer value") 

print (r1) 
」に定義されていません
+4

正しくコードをインデントし、実際に何を教えてくださいハプニング。 – donkopotamus

+0

'N 'の値は何ですか? – Evert

+0

@donkopotamus思い出してくれてありがとう、私は質問とコードを書き直しました。 – Shengjing

答えて

0

編集答え:これに

def setData(self, height, width): 
    if type(height) != int or type(width) != int: 
    raise TypeError() 
    if height <0 or width <0: 
    raise ValueError() 
    self.height = height 
    self.width = width 

:これを変更します。 @Evertによれば、Nは定義されていないので、Pythonは変数Nが何であるかを探していて、何も見つけられません。代わりに "N"(文字列にする)を書いた場合、プログラムはTypeErrorを返さなければなりません。

class Rectangle: 
    def __init__ (self): 
     self.height = 0 
     self.width = 0 

    def setData(self, height, width): 
     if type(height) != int or type(width) != int: 
      raise TypeError() 
     if height <0 or width <0: 
      raise ValueError() 
      self.height = height 
      self.width = width 

    def __str__(self): 
     return "height = %i, and width = %i" % (self.height, self.width) 

r1 = Rectangle() 
try: 
     r1.setData("N",5) 
except ValueError: 
    print ("can't set the Rectangle to a negative number") 
except TypeError: 
    print ("can't set the Rectangle to a non-integer value") 

print (r1) 

これはアウト出力します は「非整数値に四角形を設定することはできません 高さ= 0、幅= 0」

+0

これは、回答よりも「再生できません」というコメントが適切です。 – tdelaney

0

この質問のように、typeofを使用することを検討してください:Checking whether a variable is an integer or not

あなたはあなたのリストにいくつかの悪いの書式を持って、道で。新しい、より正確な説明を反映する

def setData(self, height, width): 
    if type(height) != int or type(width) != int: 
     raise TypeError() 
    if height <0 or width <0: 
     raise ValueError() 
    self.height = height 
    self.width = width 
+1

あなたは「isinstance」を意味しましたか?これは 'int'から継承したクラスをカバーしますが、OPの問題を解決することはできません。 – tdelaney

関連する問題