2016-07-21 19 views
0

Pythonで特定の無効な属性呼び出しに対してカスタムエラーメッセージを定義するにはどうすればよいですか?私はクラスのthatsが割り当て属性書い無効な属性呼び出しでのカスタムエラーメッセージの定義

は、インスタンスの作成時に入力に依存しており、割り当てられていない属性が呼び出された場合、より詳細なエラーメッセージを返すのが好き:

実行に
class test: 
    def __init__(self, input): 
     if input == 'foo': 
      self.type = 'foo' 
      self.a = 'foo' 
     if input == 'bar': 
      self.type = 'bar' 
      self.b = 'bar' 

class_a = test('foo') 

print class_a.a 
print class_a.b 

私は、このエラー・メッセージが表示されます

AttributeError: test instance has no attribute 'b' 

その代わりの私は

AttributeError: test instance is of type 'foo' and therefore has no b-attribute 
+0

'input'と' type'はPythonの予約語です。それらを使用しないことをお勧めします – alanvitor

答えて

1
のようなものを取得したいのですが

あなたのクラスにgetattrを上書きします。 Pythonは、通常の属性を見つけることができないとき

class test(object): 
    def __init__(self, input): 
     if input == 'foo': 
      self.type = 'foo' 
      self.a = 'foo' 
     if input == 'bar': 
      self.type = 'bar' 
      self.b = 'bar' 

    def __getattr__(self, attr): 
     raise AttributeError("'test' object is of type '{}' and therefore has no {}-attribute.".format(self.type, attr)) 

GETATTRが呼び出されます。基本的には、クラスがAttributeErrorを発生させるときには「except」節のようになります。

関連する問題