In the code below, AttributeError occurs because the name attribute is not set in the Test class.
test_code.py
class Test:
def __init__(self, cd):
self.cd = cd
test = Test("c001")
print(test.cd) #c001
print(test.name) # AttributeError
When writing code that anticipates that the attribute does not exist, it is good to use getattr as follows.
https://docs.python.org/3.5/library/functions.html#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")) #Since there is no attribute name, the default value is displayed
Recommended Posts