LoginSignup
2
2

More than 5 years have passed since last update.

AttributeError に備えてデフォルト値を設定するコード

Posted at

Python でコードを書くときはAttributeErrorが発生することを注意する必要がある

以下のコードでは、Testクラスにname属性が設定されていないため、AttributeErrorになる。

test_code.py
class Test:
     def __init__(self, cd):
            self.cd = cd


test = Test("c001")
print(test.cd) #c001
print(test.name) # AttributeError

属性が存在しないことを見越したコードを書く際は、以下のように getattrを使うと良い。

test_code2.py
class Test:
     def __init__(self, cd):
            self.cd = cd


test = Test("c001")
print(test.cd) #c001
print(getattr(test, "name", "default value")) # 属性nameがないので、default value が表示される 
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2