I frequently need to check if an instance of a class has a property and if that property exists, make a comparison with its value. Is there no way to do it besides the following?
if house.garage:
if house.garage == '3 car':
# do something with house.garage
Instead of using the dot notation, you can make a call to getattr
, which can return a default value if the named attribute does not exist:
if getattr(house, 'garage', "") == '3 car':
# proceed
If house
does not have an attribute named 'garage', getattr
just needs to evaluate to something that does not equal '3 car'.
You can "consolidate conditional expression" as outlined by Martin Fowler here: http://sourcemaking.com/refactoring/consolidate-conditional-expression#permalink-15
Essentially, any if statement that contains another if statement inside it is really just 1 if statement with an and in between!
if house.garage:
if house.garage == '3 car':
# do something with house.garage
becomes
if house.garage and house.garage == '3 car':
# do something with house.garage
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.