[英]Can python's dir() return attributes that are not in the object?
运行以下代码行时:
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.在上面的行中打印dir(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.