我尝试了下一个代码:
>>> f = object()
# It's obvious behavior:
>>> f.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
# However, the next one is surprising me!
>>> getattr(f, 'foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
# And this one returns None as expected:
>>> getattr(f, 'foo', None)
Run Code Online (Sandbox Code Playgroud)
然后我getattr()在PyCharm IDE中找到了这个伪签名:
def getattr(object, name, default=None): # known …Run Code Online (Sandbox Code Playgroud)