python的dir()可以返回不在对象中的属性吗?



运行以下代码行时:

variables = [at for at in dir(prev.m) if (not at.startswith('__') and (getattr(prev.m, at)==None or not callable(getattr(prev.m, at))))]

我得到以下错误:

AttributeError: 'UserClientDocument' object has no attribute 'profile'

从python文档来看,这似乎意味着它不是对象的成员。但是:1.上面一行中的打印目录(prev.m)显示"profile"为成员之一2.行本身似乎在检查检查的所有属性都应该在dir(prev.m)中

我唯一的猜测是,dir()必须将"profile"作为属性之一,而不是。这是正确的吗?还有其他选择吗?

python文档让我怀疑dir()可能不是100%准确的:

注意:由于提供dir()主要是为了方便在交互式提示下使用,因此它试图提供一组有趣的名称,而不是提供一组严格或一致定义的名称,并且它的详细行为可能会随着版本的不同而变化。例如,当参数是类时,元类属性不在结果列表中。

是的,很容易。简单示例:

class Example(object):
@property
def attr(self):
return self._attr
x = Example()
print('attr' in dir(x))  # prints True
getattr(x, 'attr')       # raises an AttributeError

实际上,dir可以返回任何名称:

class Example(object):
def __dir__(self):
return ['foo', 'bar', 'potatoes']
print(dir(Example()))  # prints ['bar', 'foo', 'potatoes'] (sorted, because dir does that)

最新更新