在 python 中使用 hasattr 而不是 hasattr

iam*_*ser 4 python

我需要使用 pythonhasattr来实现我的特定目的。我需要检查一个对象是否具有一个属性,并且没有另一个属性。

考虑名为 的类对象model,我需要检查它是否具有名为 的属性domain_id:

if hasattr(model, 'domain_id'):
Run Code Online (Sandbox Code Playgroud)

我还需要检查另一个条件,即它不应该具有名为 的属性type。

if not hasattr(model, 'type'):
Run Code Online (Sandbox Code Playgroud)

这里如何将这两个检查结合起来?

Mar*_*ers 6

只需将两个条件结合起来and:

if hasattr(model, 'domain_id') and not hasattr(model, 'type'):
Run Code Online (Sandbox Code Playgroud)

仅当两个条件都为真时该if块才会执行。