Can python's dir() return attributes that are not in the object?

时间:2017-11-13 06:09:14

标签: python class

When running the following line of code:

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))))]

I get the following error:

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

which from the python documentation seems to mean that it's not a member of the object. However: 1. Printing dir(prev.m) in the line above shows 'profile' as one of the members 2. The line itself seems to be checking that all attributes checked should be in dir(prev.m)

My only guess is that dir() must give 'profile' as one of the attributes, when it is not. Is that correct? Any other options?

The python documentation making me suspect that dir() may not be 100% exact:

Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

1 个答案:

答案 0 :(得分:-1)

Yeah, easily. Simple example:

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

And really, dir can return any names at all:

class Example(object):
    def __dir__(self):
        return ['foo', 'bar', 'potatoes']

print(dir(Example()))  # prints ['bar', 'foo', 'potatoes'] (sorted, because dir does that)