2011-12-29 15 views
0

を上げることは、私のコードです:xlongInputExceptionさんexcept文で使用されている理由は、ここでの例外の問題

class longInputException(Exception): 
    def __init__(self, length, max): 
     Exception.__init__(self) 
     self.length = len(length) 
     self.max = max 

try: 
    max = 3 
    s = raw_input('Enter something-->') 
    if len(s) > max: 
     raise longInputException(s, max) 

except longInputException, x: 
    print 'longInputException: the input was of length %d, \ 
was expecting less than or equal to %d' % (x.length, x.max) 

else: 
    print 'No exception was raised.' 

私は理解していないことです。代わりのタプルでselfを使っただけではどうですか?

答えて

3

selfは(あなたが__init__()の定義の最初の引数としてselfを提供しているため)__init__()メソッド内で、現在のオブジェクトの名前であり、それ以外ではアクセスできません。

(これは、あなたが何をすべきないものですが、これは変数があるかについて人々を混乱させる可能性として、)必要に応じてあなたがそのような何かを行うことができます。

except longInputException, self: 
    print 'longInputException: the input was of length %d, \ 
was expecting less than or equal to %d' % (self.length, self.max) 

else: 
    print 'No exception was raised.' 

それは、あなたの質問に答えるのか?

Pythonのクロージャと名前空間については、こちらをご覧ください。

0

try ... exceptステートメントが別のクラスのインスタンス化であり、exceptステートメントで「self」を使用した場合、「self」はインスタンス化された例外クラスではなく、インスタンス化されたクラスを参照します。

0

私はそれはあなたが例外のどのインスタンスを参照していたかわからないためだと思います。とにかく、オブジェクトの内部では、通常、「自己」のみを使用します。