简体   繁体   English

检查存在和是否存在是一定的值

[英]Checking existence and if exists, is a certain value

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: 您可以调用getattr而不是使用点表示法,如果命名属性不存在,则可以返回默认值:

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'. 如果house没有名为'garage'的属性, getattr只需要评估一些不等于'3 car'的东西。

You can "consolidate conditional expression" as outlined by Martin Fowler here: http://sourcemaking.com/refactoring/consolidate-conditional-expression#permalink-15 你可以像Martin Fowler在这里所说的那样“巩固条件表达式”: 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语句的if语句实际上只是1,如果语句带有和之间的!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM